Android Volley Library: Do We Always Have To Repeat Response.listener And Response.errorlistener
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 jsonObjReq = new JsonOb
Solution 1:
You can refer to my sample code as the following:
publicinterfaceVolleyResponseListener {
voidonError(String message);
voidonResponse(Object response);
}
Then in my VolleyUtils class:
publicstaticvoidmakeJsonObjectRequest(Context context, String url, final VolleyResponseListener listener) {
JsonObjectRequest jsonObjectRequest = newJsonObjectRequest
(url, null, newResponse.Listener<JSONObject>() {
@OverridepublicvoidonResponse(JSONObject response) {
listener.onResponse(response);
}
}, newResponse.ErrorListener() {
@OverridepublicvoidonErrorResponse(VolleyError error) {
listener.onError(error.toString());
}
}) {
@OverrideprotectedResponse<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = newString(response.data,
HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET));
returnResponse.success(newJSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
returnResponse.error(newParseError(e));
} catch (JSONException je) {
returnResponse.error(newParseError(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!
Solution 2:
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.
Post a Comment for "Android Volley Library: Do We Always Have To Repeat Response.listener And Response.errorlistener"