Reputation: 3383
I understand that POST requests using JsonArrayRequest are not available out of the box with Volley, but I saw this post here that talked about adding a constructor to handle this. Their implementation was this:
public JsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(),
listener, errorListener);
}
How would I go about adding this as a constructor? The above question mentions placing it in the Volley Tool Library. I imported Volley as a .jar, so I'm not sure how to add a constructor like this, or if this is the best approach. Any help is much appreciated.
EDIT
I've created the following class with override and constructor as suggested. Here is the class:
public class PostJsonArrayRequest extends JsonArrayRequest {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
public PostJsonArrayRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(Method.POST, url, null, listener, errorListener);
}
}
On the line calling super I'm getting The constructor JsonArrayRequest(int, String, null, Response.Listener<JSONArray>, Response.ErrorListener) is undefined
How do I correct this?
Upvotes: 2
Views: 4492
Reputation: 7696
Create a class and extend JsonArrayRequest
then override
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
and add a new constructor and in it call
super(Method.POST, url, null, listener, errorListener);
or use this class
public class PostJsonArrayRequest extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* @param url URL to fetch the JSON from
* @param listener Listener to receive the JSON response
* @param errorListener Error listener, or null to ignore errors.
*/
public PostJsonArrayRequest(String url, Response.Listener<JSONArray> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, null, listener, errorListener);
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "value");
return params;
}
@Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
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));
}
}
}
Upvotes: 2