在排球请求中将arraylist作为参数发送

时间:2016-04-20 11:03:29

标签: android android-volley jsonexception

我试图在排球请求中发送包含数字的arraylist作为参数,然后解析它并在toast中显示值(以字符串形式)。但是我的回答是空的。我想知道问题出在哪里。



json response:

{
  "got_members": [
    "1",
    "2"
  ]
}

public class SearchFragment extends Fragment{

    Button checkme;
    private static final String ADDMEM = "http://www.example.com/api/event/addmembers/", KEY_ADDMEM = "adding_members";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.searchfragment, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        checkme = (Button)view.findViewById(R.id.checkme);
        checkme.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                checkarraylist();

            }
        });
    }

    private void checkarraylist(){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, ADDMEM,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        if(response != null){
                            try {
                                JSONObject object = new JSONObject(response);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                        }else {

                            Toast.makeText(getActivity(), response, Toast.LENGTH_SHORT).show();
                            try {

                                JSONArray itemArray = new JSONObject(response).getJSONArray("got_members");
                                for (int i = 0; i < itemArray.length(); i++) {
                                    String value = itemArray.getString(i);
                                    Toast.makeText(getActivity(), "Result:" + value + "\n", Toast.LENGTH_SHORT).show();
                                }


                            } catch (JSONException e) {
                                // JSON error
                                e.printStackTrace();
                                Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                            }

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                ArrayList<String> strings = new ArrayList<String>();
                strings.add("10");
                strings.add("20");
                strings.add("30");
                Map<String, String> params = new HashMap<String, String>();
                int i=0;
                for(String object: strings){
                    params.put("adding_members["+(i++)+"]", object);
                    System.out.println(object);
                }

           /*    String array[]=strings.toArray(new String[strings.size()]);

                for(String k: array)
                {

                    params.put("adding_members", k);
                    System.out.println(k);
                } */



                return params;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                params.put("Content-Type", "application/x-www-form-urlencoded;  charset=utf-8");
                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }




}
&#13;
&#13;
&#13;

6 个答案:

答案 0 :(得分:2)

首先在ArrayList中的Object中:创建JSONObjectmethod名称作为getJSONObject,就像这样

public class EstimateObject {
String id, name, qty, price, total;
public EstimateObject(String id, String name, String qty, String price, String total, int position)
{
    this.id = id;
    this.name = name;
    this.qty = qty;
    this.price = price;
    this.total =total;
    this.position = position;
}
 public JSONObject getJSONObject() {
    JSONObject obj = new JSONObject();
    try {
        obj.put("Id", id);
        obj.put("Name", name);
        obj.put("Qty",qty);
        obj.put("Price", price);
        obj.put("Total", total);
    }
    catch (JSONException e) {
        e.printStackTrace();
    }
    return obj;
}

Aftrer以下是我在活动中如何转换它

    JSONObject JSONestimate = new JSONObject();
    JSONArray myarray = new JSONArray();

    for (int i = 0; i < items.size(); i++) {

        try {
            JSONestimate.put("data:" + String.valueOf(i + 1), items.get(i).getJSONObject());
            myarray.put(items.get(i).getJSONObject());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    Log.d("JSONobject: ", JSONestimate.toString());
    Log.d("JSONArray : ", myarray.toString());

这里我转换了JSONObject和JSONArray类型。

之后

map.put("jsonarray",myarray.toString());

答案 1 :(得分:1)

您必须先解析JSONObject。然后获取JSONArray。像这样 - &gt;

try {
    JSONArray array = new JSONObject(response).getJSONArray("got_members");
    for (int i = 0; i < itemArray.length(); i++) {
        String value=itemArray.getString(i);
        //Log.e("json", i+"="+value);
        Toast.makeText(getActivity(), "Result:" + value+"\n", Toast.LENGTH_SHORT).show();
    }
} catch (JSONException e) {
    e.printStackTrace();
}

答案 2 :(得分:1)

您需要添加以下代码以及重写的getParams()函数

@Override
        protected Map<String, String> getParams() {
//Parameters added here
}

@Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/x-www-form-urlencoded;  charset=utf-8");
            return params;
        }

您还需要更改此行

JSONArray itemArray = new JSONArray("got_members");

JSONArray itemArray = new JSONObject(response).getJSONArray("got_members");

答案 3 :(得分:1)

这可能是迟到的反应,但根据反应示例,​​这可能会有所帮助

try {
        JSONObject object = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (int i = 0; i < 2; i++) {
            String someString = String.valueOf(i);
            jsonArray.put(someString);
        }
        object.put("got_members", jsonArray);
    } catch (JSONException e) {
        e.printStackTrace();
    }

答案 4 :(得分:0)

首先在JsonObject中获取响应,然后检索JsonArray或将字符串请求更改为JsonArray请求

 try {
      JsonObject object=new JsonObject(response)

                            JSONArray itemArray = new JSONArray("got_members");
                            for (int i = 0; i < itemArray.length(); i++) {
                                String value=itemArray.getString(i);
                                //Log.e("json", i+"="+value);
                                Toast.makeText(getActivity(), "Result:" + value+"\n", Toast.LENGTH_SHORT).show();
                            }



                    } catch (JSONException e) {
                        // JSON error
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }

或仅使用JSONArray array = new JSONObject (response).getJSONArray("got_members");

答案 5 :(得分:0)

尝试此操作而不是发送整个arraylist,如果您要发送联系

@Override
        protected Map<String, String> getParams() throws AuthFailureError {

            ArrayList<String> numbers = new ArrayList<String>();
            Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);

            while (phones.moveToNext())
            {
                String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
               numbers.add("\n"+name+"\n"+phoneNumber+"\n");

            }
            phones.close();

            Map<String, String> params = new HashMap<String, String>();

            int i=0;
            for(String object: numbers){
                params.put("a"+(i++), object);
             if(i==10)
               break;
            }
            return params;
  

现在在服务器端处理此问题

$response=array();$response["res"]=array(); foreach($_POST as $k => $v) {
if(strpos($k, 'a') === 0) {
    $res=array();
    $ab=$k = $v;
    $res["name"]=$ab;array_push($response["res"],$res);}}echo json_encode($response);
  

现在回复后

@Override
        public void onResponse(String response) {

            try {

                JSONObject stdent = new JSONObject(response);
                JSONArray students = stdent.getJSONArray("res");
                for (int i = 0; i < students.length(); i++) {
                    String ab=students.getString(i);
                    Toast.makeText(getApplicationContext(),  ab, Toast.LENGTH_LONG).show();

                }