I have recently started using Android Volley in my project. The common practice mentioned in most of the tutorials is to use it this way:
JsonObjectRequest
Create a class (like "ApiManager") that you pass the url and parameters, that creates the Volley request and keeps track of the replies and listeners. The ApiManager would typically get a callback from the calling class for the results. This way, you have to type the Volley code only once, while the logic for each call would be concise. Or, that's how I do it.
You can refer to my sample code as the following:
public interface VolleyResponseListener {
void onError(String message);
void onResponse(Object response);
}
Then in my VolleyUtils class:
public static void makeJsonObjectRequest(Context context, String url, final VolleyResponseListener listener) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
listener.onResponse(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
listener.onError(error.toString());
}
}) {
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
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));
}
}
};
// Access the RequestQueue through singleton class.
VolleySingleton.getInstance(context).addToRequestQueue(jsonObjectRequest);
}
Then in Activity:
VolleyUtils.makeJsonObjectRequest(mContext, url, new VolleyResponseListener() {
@Override
public void onError(String message) {
}
@Override
public void onResponse(Object response) {
}
});
Another way is creating a VolleyResponseListener variable then passing it into methods of VolleyUtils class, as my answer in the following question:
Android: How to return async JSONObject from method using Volley?
Hope this helps!