0

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




}
Somnath Pal
  • 1,570
  • 4
  • 23
  • 42

6 Answers6

3

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());
Pravin Suthar
  • 1,403
  • 1
  • 14
  • 25
1

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();
}
Zahidul Islam
  • 3,180
  • 1
  • 25
  • 35
1

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");
nitinkumarp
  • 2,120
  • 1
  • 21
  • 30
  • I changed my way of sending parameter by converting the arraylist to string. But now I'm only getting value "20" and not "10". – Somnath Pal Apr 20 '16 at 12:15
  • 1
    `for(String k: array) { params.put("adding_members", k); }` you are putting same key for multiple value. If key is same in HashMap it will replace previous data. – nitinkumarp Apr 20 '16 at 13:04
  • Its the same as my code. I'm still getting the last value only in response. @nitinkumarp – Somnath Pal Apr 20 '16 at 13:08
  • 1
    I am saying that your previous code was correct. The code I posted in comment is your and I am saying to revert. – nitinkumarp Apr 20 '16 at 13:11
  • But with previous code I was not getting anything in response and I think it was due to `"adding_members["+(i++)+"]"` in params.put(). @nitinkumarp – Somnath Pal Apr 20 '16 at 13:14
  • I don't think it would cause any problem – nitinkumarp Apr 20 '16 at 13:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/109686/discussion-between-somnath-pal-and-nitinkumarp). – Somnath Pal Apr 20 '16 at 13:19
1

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();
    }
Hemanth S
  • 669
  • 6
  • 16
  • its not working for me https://stackoverflow.com/questions/51206258/how-to-add-list-into-params-of-volley-android?noredirect=1#comment89393472_51206258 please help me i want to add list into params of volley android –  Jul 06 '18 at 09:51
0

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

Ameer
  • 2,709
  • 1
  • 28
  • 44
  • Your code is not correct . `JSONArray itemArray = new JSONArray("got_members");` This line should be `object.getJSONArray("got_members")` – Zahidul Islam Apr 20 '16 at 11:13
  • Both answers are same but after changing it in my code I'm not getting any Toast. I should be getting the "String value" in toast – Somnath Pal Apr 20 '16 at 11:19
  • Where you want to add that toast. You want multiple toast or single toast. ??. Thanks Zainul Islam for ur suhhestion – Ameer Apr 20 '16 at 11:24
  • I checked the "response" in Toast, I'm getting `{"got_members":[]}`. This means, the arraylist in parameter is not being sent properly. – Somnath Pal Apr 20 '16 at 11:25
  • Yes. You are right. If the response is empty then your toast will not show. – Ameer Apr 20 '16 at 11:26
  • If the response is { "got_members": [ "1", "2" ] } this, then two times toast will display – Ameer Apr 20 '16 at 11:27
  • So, is there any better way to send arraylist as parameter in volley post request? As its clear that the fault is in parameter @Ameer. – Somnath Pal Apr 20 '16 at 11:27
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/109663/discussion-between-ameer-and-somnath-pal). – Ameer Apr 20 '16 at 11:28
  • It should be `JSONArray array = new JSONObject (response).getJSONArray("got_members");` – nitinkumarp Apr 20 '16 at 11:29
0

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

                }
Adiii
  • 54,482
  • 7
  • 145
  • 148