6

To say in simple words i want to send this {"Id":7,"Name":"MyName"} data To server using Volley Post Request.

It has 1 integer and 1 String and response i get is Jsonarray

I tried Following ways but none are working

  • as it is json array request i cannot send data in argument as 3rd argument only takes JsonArray and i have to send JsonObject so kept it as null

    new JsonArrayRequest(Method,Url,JsonArray,ResponseListener,ErrorListner)

  • I cannot put it in HashMap as 1 of the value is integer, and it only accepts string

getparams() method

@Override
protected Map<String, String> getParams() throws AuthFailureError {
    Map<String,String> params=new HashMap<>();
    params.put("Id",7); //            <====== This is Invalid
    params.put("Name","MyName");
    return params;
}
  • I tried to send in getbody method ,still not working

getbody method

@Override
public byte[] getBody() {
    String body="{\"Id\":7,\"Name\":\"MyName\"}";
    return body.getBytes();
}

I can get the response using HttpUrlConnection.

Is there any other way to achieve it in volley ?

0

5 Answers 5

6

Thanks to akash93 , i finally did it .Here is how to do it

write a class MyJsonArrayRequest.java like below

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
public class MyJsonArrayRequest extends JsonRequest<JSONArray> {


    public MyJsonArrayRequest(int method, String url, JSONObject jsonRequest,
                              Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
    }

    @Override
    protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
            return Response.success(new JSONArray(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

usage :

 MyJsonArrayRequest request=new MyJsonArrayRequest(Request.Method.POST, Constants.SEARCH_PROFILE, object, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            Log.i("onResponse", ""+response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
            Log.i("onErrorResponse", "Error");
        }
    });

even more easier way is to override getBody() which should work , but some way it didn't work for me first time.

 @Override
public byte[] getBody() {
    String body="{\"Id\":7,\"Name\":\"MyName\"}";
    return body.getBytes();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks this works for me. I have to post JsonArrayRequest and response is as JsonObject.
2

Seems like it was removed in recent volley version but you can easily modify this constructor and add to JsonArrayRequest.

public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
                            Listener<JSONArray> listener, ErrorListener errorListener) {
        super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
    }

Comments

1
 JSONObject jsonObject = new JSONObject();
    try {
        // user_id, comment_id,status
        jsonObject.put("user_id", your_data);
        jsonObject.put("comment_id", your_data);
        jsonObject.put("status", your_data);
        jsonObject.put("token", your_data);
    } catch (Exception e) {
        e.printStackTrace();
    }

 JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
            YOUR_API _NAME, jsonObject,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

 //  YOUR RESPONSE 
}
   }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();

        }
    });
   mRequestQueue.add(jsonObjReq);

// } }

Comments

0

try this :

new JsonArrayRequest(Method,Url,JsonArray,ResponseListener,ErrorListner) 

change to

new JsonObjectRequest(Method,Url,JsonArray,ResponseListener,ErrorListner)

Comments

0

Why don't you send params.put("Id",""+7); and then in your backend script you can typecast it to integersay for eg in php

$id_input = (int)mysqli_real_escape_string($conn,$_POST['Id'])

1 Comment

Id show be an integer , We should not change backend code to fix a bug in android.

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.