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

asked Apr 20, 2016 at 11:03

6 Answers 6

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());
answered Feb 2, 2017 at 11:04
Sign up to request clarification or add additional context in comments.

Comments

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();
}
answered Apr 20, 2016 at 11:08

Comments

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");
answered Apr 20, 2016 at 11:38

7 Comments

I changed my way of sending parameter by converting the arraylist to string. But now I'm only getting value "20" and not "10".
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.
Its the same as my code. I'm still getting the last value only in response. @nitinkumarp
I am saying that your previous code was correct. The code I posted in comment is your and I am saying to revert.
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
|
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();
 }
answered Feb 2, 2017 at 12:11

1 Comment

its not working for me stackoverflow.com/questions/51206258/… please help me i want to add list into params of volley android
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");

answered Apr 20, 2016 at 11:08

9 Comments

Your code is not correct . JSONArray itemArray = new JSONArray("got_members"); This line should be object.getJSONArray("got_members")
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
Where you want to add that toast. You want multiple toast or single toast. ??. Thanks Zainul Islam for ur suhhestion
I checked the "response" in Toast, I'm getting {"got_members":[]}. This means, the arraylist in parameter is not being sent properly.
Yes. You are right. If the response is empty then your toast will not show.
|
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();
 }
answered Jul 4, 2016 at 1:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.