This repository was archived by the owner on Feb 26, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
This repository was archived by the owner on Feb 26, 2018. It is now read-only.
POST JsonObject with different data types (int, boolean etc.) params and get JsonArray response #169
Copy link
Copy link
Open
Description
I had to call json array post request with integer and string params. Firstly I tried with string request but when string request is used your hash map params must be string values.
After that I solved the problem with this way;
I have create CustomRequest class;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
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 CustomRequest extends JsonRequest<JSONArray> {
public CustomRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
super(Method.GET, url, null, listener, errorListener);
}
public CustomRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, 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));
}
}
}
and I used the class like this way;
CustomRequest customRequest = new CustomRequest(Request.Method.POST, url, (params != null) ? new JSONObject(params) : null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
callback.onSuccessResponse( response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
callback.onErrorResponse(error);
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
return params;
}
};
I hope this solution also helps someone else who has this problem
Metadata
Metadata
Assignees
Labels
No labels