send arraylist as parameter in volley request

喜欢而已 提交于 2019-12-23 05:26:00

问题


I'm trying to send arraylist containing numbers as parameter in volley request and then parse it and display the values (in string) in toast. But I'm getting null in response. I would like to know where is the problem.

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);
    }




}

回答1:


First in your Object in ArrayList: create JSONObjectmethod name as getJSONObject, like this

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 Here is how I converted it,in my activity

    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());

Here i converted both type JSONObject and JSONArray.

After in

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



回答2:


You have to parse the JSONObject first . Then get the JSONArray . like this way ->

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();
}



回答3:


You need to add the following code alongwith your overriding getParams() function

@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;
        }

Also you need to change this line

JSONArray itemArray = new JSONArray("got_members");

to

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



回答4:


This may be the late response but as per response example this could help a bit

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();
    }



回答5:


First get the response in JsonObject and then retreive the JsonArray or change the string request to JsonArray request

 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();
                    }
                }

or simply use JSONArray array = new JSONObject (response).getJSONArray("got_members");




回答6:


try this instead of sending whole arraylist,if you are sending contact

@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;

now handle this on server side

$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);

now after 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();

                }


来源:https://stackoverflow.com/questions/36741810/send-arraylist-as-parameter-in-volley-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!