Android Custom Volley Request
There are inbuilt requests that Volley supports. Also it allows the developers to customize their requests. What does customizing the request mean? Why is it needed? Here’s the answer! Before jumping into the below description, I recommend you to have a bird’s view on the below link where I have explained about Volley architecture.
What are inbuilt volley requests? 🤨
These requests are the ones that are readily available in volley toolbox. Few of them are String request, JsonObjectRequest, Image request etc.,
If you need String response as your output, choose String request. For JSONObject response use JsonObjectRequest. For JSONArray as your response, choose JsonArrayRequest. Okay hold on! Stop reading it in the tone of customer care recorded voice 🤐
These are the standard requests that the developers can directly make use of.
Why Custom Volley request? 😐
Let’s say that I need “Weather” response in the success listener. What will I do? Ummm… Maybe I can use Gson to convert the json response to “Weather” POJO class. This conversion will be done in main thread [Volley always makes sure that the result we receive will be handed over to main thread]
So, you are thinking, “Eh! 😏 if that’s the case, create an Async task, do that stuff in background” right??? Well you are right. But why would you do all these if Volley does it for you? Yes! This is where the concept of Custom Volley request comes into picture.
So if you need the response of your type, go for Custom volley request!
Need for Custom Volley request
Let’s say that you have created a beautiful app that displays network contents on the UI. To display it, there can be n number of filtration operations you are performing in onSuccess() method.
Before the final app release, your testing teammates raise a critical bug saying navigation is not smooth! 😛😛
We crack our head thinking for the reason and finally end up saying it as an Android limitation [RecyclerView issue] 🙊
In case of ANR’s, lag in navigation, start profiling your App. There’s CPU profiling method tracing that helps to know how much time your function is taking to perform some set of operations.
When it comes to heavy filtration operation in onSuccess() of your Volley response, let us assume there is a huge for loop running that exceeds more than 5s or parsing your response to POJO on main thread might take more than 150 ms. This indeed will downgrade your App performance with jerky scrolling or throws App not responding message that will irritate the user.
So, one of the methods where we can avoid such things is by performing these filtration and parsing of response on background thread.
Procedure to create Custom Request class:
Step 1: Create your custom request class by extending Request class
Step 2: Override parseNetworkResponse() and deliverResponse()
Step 3: Notify your listeners
and you are done!
Step 1: Create your custom request class
Custom Volley is not only required to get response of the type we want but also help us by providing a method to carry out the filtration operations in background thread. Let us create CustomRequest class by extending Request class of type T
public class CustomRequestClass<T> extends Request<T> {
}
Once the above thing is done, create the constructor and override 2 methods
- Create constructor:
The constructor contains the parameters: request method, url, error listener by default. MySuccessListener is the interface that has notifyMyObservers(Object response) method in it. This will help us in getting customized type response. So while requesting, we need to add this parameter.
public CustomRequestClass(int method, String url, MySuccessListener mySuccessListener, Response.ErrorListener listener, T responseClass) {
super(method, url, listener);
successListener = mySuccessListener;
this.responseClass = responseClass;
}
2. parseNetworkResponse():
This is something that runs on background thread that helps performing parsing or filtering by reducing stress on main thread.
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response {
//TODO: Runs on background thread String json = null;
try {
json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} // Parsing and other filtration can be carried out here
T respGson = (T) gson.fromJson(json, responseClass.getClass());
return Response.success(respGson,
HttpHeaderParser.parseCacheHeaders(response));
}
3. deliverResponse():
This runs on main thread by notifying the listeners with the type of response that request had requested for.
@Override
protected void deliverResponse(T response) {
successListener.notifyMyObservers(response);
}
Snippet to understand calling mechanism of Custom request
Step 1: Create the object of customized success listener class
MySuccessListener mySuccessListener = new MySuccessListener() {
@Override
public void notifyMyObservers(Object responseClass) { // This is where you get the actual success response.
// So typecast the response of object class to your response ResponseClass myResponse = (ResponseClass) responseClass;
}
};
Step 2: Form the request
The parameters that are sent: Request method, url, success and error listeners, the class that I want as response [See above snippet for understanding why response class is sent as last parameter. It helps while converting response to the Java class we requested for, using Gson]
CustomRequestClass<ResponseClass> customRequestClass = new CustomRequestClass<>(Request.Method.GET, url, mySuccessListener, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: error "+error.getMessage());
}
}, new ResponseClass());
Step 3: Don’t forget to add your request to the request queue 😛
CustomVolley.getInstance().addToRequestQueue(customRequestClass,
TAG);
So, this is all about custom volley. Stay tuned for updates! 🙋🏻