how to send array of params using volley in android

27,683

Solution 1

Use

HashMap<String ,String> params=new HashMap<String, String>(7);
for(int i=1;i<=7;i++)
{
    params.put("params_"+i, arr[i]);
}

in CustomJobjectRequest class because currently you are using String type as value in Map in CustomJobjectRequest class but sending String[] type when create object of CustomJobjectRequest class.

Edit:

To send all values in single parameter to server use JSONObject.Create a json object using all key-value as:

 JSONObject jsonObject=new JSONObject();
 for(int i=1;i<=7;i++)
    {
        arr[i]="questionId_"+i+"_"+"ans_"+i;
        jsonObject.put("params_"+i,arr[i]);
    }
HashMap<String ,String> params=new HashMap<String, String>();
params.put("params",jsonObject.toString());

TO send all values on server side get params and convert to JSON object and iterate to get all values

Solution 2

Use

    Map<String, String> postParam = new HashMap<>();
    int i=0;
    for(String object: friendIds){
        postParam.put("friendIds["+(i++)+"]", object);
        // you first send both data with same param name as friendnr[] ....  now send with params friendnr[0],friendnr[1] ..and so on
    }

this work for me, hope it work to you.

Share:
27,683
TechChain
Author by

TechChain

I have 4+ of experience of overall experience.Currently working on Hyperledger Fabric blockchain framework. I have strong knowledge of Objective c, Swift.I have developed lot of apps from chat app, finance apps,location &amp; map based apps.

Updated on July 23, 2022

Comments

  • TechChain
    TechChain almost 2 years

    I am developing an application which send lot of data to server.Now i want to send an array of params to a php page using volley.But i am not able to send it.

    Code for adding params as Array.

    String[] arr =new String[7];
        for(int i=1;i<=7;i++)
        {
            arr[i]="questionId_"+i+"_"+"ans_"+i;
    
        }
        HashMap<String ,String[]> params=new HashMap<String, String[]>(7);
        params.put("params", arr);
    

    Code for making request to server

    RequestQueue que=Volley.newRequestQueue(this);
    
         final ProgressDialog dialog = new ProgressDialog(HealthMyHistory.this);
         dialog.setTitle("Please Wait");
         dialog.setMessage("Sending Data");
         dialog.setCancelable(false);
         dialog.show();
    
    
        CustomJobjectRequest jsObjRequest = new CustomJobjectRequest(Method.POST, url, params, new Response.Listener<JSONObject>() {
    
                    @Override
                    public void onResponse(JSONObject response)
                    {
                        dialog.dismiss();
    
    
    
                    }
                }, new Response.ErrorListener() {
    
                    @Override
                    public void onErrorResponse(VolleyError response) {
    
                        dialog.dismiss();
                        Toast.makeText(getApplicationContext(), "Unable to Send Data!"+" "+response.toString(), Toast.LENGTH_SHORT).show();
                    }
                });
        que.add(jsObjRequest);
    
    }
    
    
    
    Problem is in CustomJobjectRequest there is no constructor available of type in which Hashmap accepts string & array as argument.How to do it ? 
    

    Code or CustomJsonObjectRequest

     package com.example.healthcoach.data;
    
    import java.io.UnsupportedEncodingException;
    import java.util.HashMap;
    import java.util.Map;
    
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import com.android.volley.NetworkResponse;
    import com.android.volley.ParseError;
    import com.android.volley.Request;
    import com.android.volley.Response;
    import com.android.volley.Response.ErrorListener;
    import com.android.volley.Response.Listener;
    import com.android.volley.toolbox.HttpHeaderParser;
    
    
    public class CustomJobjectRequest extends Request<JSONObject>{
    
        private Listener<JSONObject> listener;
        private Map<String, String> params;
    
        public CustomJobjectRequest(String url, Map<String, String> params,
                  Listener<JSONObject> reponseListener, ErrorListener errorListener) {
              super(Method.POST, url, errorListener);
              this.listener = reponseListener;
              this.params = params;
        }
    
        public CustomJobjectRequest(int method, String url, Map<String, String> params,
                  Listener<JSONObject> reponseListener, ErrorListener errorListener) {
              super(method, url, errorListener);
              this.listener = reponseListener;
              this.params = params;
          }
    
      public CustomJobjectRequest(int post, String url,
                HashMap<String, String[]> params2, Listener<JSONObject> listener2,
                ErrorListener errorListener) {
            // TODO Auto-generated constructor stub
        }
    
    @Override
      protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        return params;
      };
    
      @Override
      protected void deliverResponse(JSONObject response) {
          listener.onResponse(response);
      }
    
      @Override
      protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
           try {
                  String jsonString = new String(response.data,
                          HttpHeaderParser.parseCharset(response.headers));
                  return Response.success(new JSONObject(jsonString),
                          HttpHeaderParser.parseCacheHeaders(response));
              } catch (UnsupportedEncodingException e) {
                  return Response.error(new ParseError(e));
              } catch (JSONException je) {
                  return Response.error(new ParseError(je));
              }
      }
    
    }
    
  • TechChain
    TechChain over 9 years
    Why can't i create a constructor which accept HashMap<String,String[]> in CustomJsonObjectRequest class?
  • ρяσѕρєя K
    ρяσѕρєя K over 9 years
    @TechGuy: getParams() or other methods which you ar eoverrding from Request<JSONObject> class is use Map<String ,String> instead of HashMap<String ,String[]> so you should use Hash<String ,String>
  • TechChain
    TechChain over 9 years
    Ok is this only way to send array of params?
  • TechChain
    TechChain over 9 years
    @prosper K sir i want get an array of params on server end as in php
  • ρяσѕρєя K
    ρяσѕρєя K over 9 years
    @TechGuy: pass Array as parameter is not possible but you can send all values in single parameter using JSONObject. create a JSONObject with all values then send it to server as HashMap<String ,String> params=new HashMap<String, String>();params.add("params", jsonobject.toString()); Now on php side convert received string from params to JSONObject to get all values
  • Admin
    Admin almost 6 years
  • sudharsan chandrasekaran
    sudharsan chandrasekaran almost 6 years
    Thanks for your idea friend. Its working for me . I have used like this Code : JSONArray jsonArray=new JSONArray(); for(int i=0;i<list.size();i++) { jsonArray.put(list.get(i)); Log.d("ClassRoomAtt", "jsonObje--->" + jsonArray.toString()); }