-2

For Ex

 [{
            "id": 1,
            "name": "Christina Walker",
            "selectedGrade": 4
        }, {
            "id": 2,
            "name": "Bond Mccormick",
            "selectedGrade": 1
        }]

like this ? Can anyone help me ? i was tried for last three days?

8
  • try to make JSONArray request. Commented Oct 4, 2017 at 4:58
  • stackoverflow.com/questions/40817362/… Commented Oct 4, 2017 at 4:59
  • in getparams it takes only string value .. but i need to pass array value . Commented Oct 4, 2017 at 5:00
  • you can send json string as parameter using volley Commented Oct 4, 2017 at 5:00
  • 1
    Possible duplicate of Send POST request with JSON data using Volley Commented Oct 4, 2017 at 5:45

1 Answer 1

2

Try following code.

   JSONObject objectJson1= new JSONObject();
   objectJson1.put("id","1");
   objectJson1.put("selectedGrade","8");
   objectJson1.put("selectedGrade","8");

//second array

   JSONObject objectJson2= new JSONObject();
   objectJson2.put("id","2");
   objectJson2.put("selectedGrade","9");
   objectJson2.put("selectedGrade","9");
   JSONArray mainArray=new JSONArray();
   mainArray.put(0,objectJson1);
   mainArray.put(1,objectJson2);
   String data=mainArray.toString();

then pass this like in volley

public void requestVolley(){
StringRequest stringRequest = null;
    final String requestBody = data;
    stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            //catch your resposne
        }
    }, new Response.ErrorListener() {

 @Override
        public void onErrorResponse(VolleyError error) {
            String json="";
            if (error.networkResponse != null) {
                // = String.valueOf(response.statusCode);
                try {
                    json = new String(
                            error.networkResponse.data, HttpHeaderParser.parseCharset(error.networkResponse.headers));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                Response<String> rr =Response.success(json, HttpHeaderParser.parseCacheHeaders(error.networkResponse));
                setCustomResponse(rr);
            }
        }
    }) {
@Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
                return null;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            String json="";
            if (response != null) {
                // = String.valueOf(response.statusCode);
                try {
                    json = new String(
                            response.data, HttpHeaderParser.parseCharset(response.headers));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                // can get more details such as response.headers
            }
            return Response.success(json, HttpHeaderParser.parseCacheHeaders(response));
        }
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Authorization", "your key if any");
            return params;
        }
    };
    stringRequest.setRetryPolicy(new DefaultRetryPolicy(
            30000,
            0,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    stringRequest.setShouldCache(false);
    YourApplicationLevelClass.volleyQueueInstance.addToRequestQueue(stringRequest);
}

Define this variable at application level public static VolleySingleton volleyQueueInstance; and define instantiateVolleyQueue at application level

public void instantiateVolleyQueue() {
    volleyQueueInstance = VolleySingleton.getInstance(getApplicationContext());
}

Create volley Singleton class

  public class VolleySingleton 
    {
    private static VolleySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;
    private RequestQueue mRequestQueuePatch;

    private VolleySingleton(Context context) {

        final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMemory / 8;

        this.mCtx = context;
        mRequestQueue = getRequestQueue();
        mImageLoader = new ImageLoader(mRequestQueue,

                new ImageLoader.ImageCache() {
                    private final LruCache<String, Bitmap>
                            cache = new LruCache<String, Bitmap>(cacheSize);

                    @Override
                    public Bitmap getBitmap(String url) {
                        return cache.get(url);
                    }

                    @Override
                    public void putBitmap(String url, Bitmap bitmap) {
                        cache.put(url, bitmap);
                    }
                });
    }

    public static synchronized VolleySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new VolleySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }
    public RequestQueue getRequestQueuePatch() {
        if (mRequestQueuePatch == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueuePatch = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueuePatch;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueuePatch(Request<T> req) {
        getRequestQueuePatch().add(req);
    }

    public <T> void cancelRequestInQueue(String tag) {
        getRequestQueue().cancelAll(tag);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
   }
Sign up to request clarification or add additional context in comments.

10 Comments

here how to convert jsonarray to jsonobject?
String data=object.toString(); just convert your json array to string and pass as string to your volley
and on server side covert your string to JSONArray and parse it
@Nanthu if answer helpful please accept this answer.
simple check my answer
|

Your Answer

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.