Volley library in Android

Volley library in Android
Volley library in Android

Volley is a reliable HTTP (HyperText Transfer Protocol) library that helps in making networking swift and efficient. It was produced by Google; it came into existence during Google I/O 2013 and was announced by Ficus Kirkpatrick.

There was a dire need of a networking class that could work abstractly, that is, without producing any interference in the user experience, in the Android SDK. Earlier Volley was an integral component of the Android Open Source Project (AOSP). The first instance at which was the Volley Library was by the Play Store team in Play Store Application. Later, in January 2017 Google declared Volley an independent library.

The volley library comes with some superior features like automated and scheduled network requests, numerous concurrent connections, we can prioritise requests in case of conflicts, inhibit or revert certain requests, it allows offer a higher degree of customisation and mostly allows us to manage user-interface with higher ease using the asynchronously fetched data from the network.

There is no need of writing boilerplate codes using AsyncTask for fetching response from Web API and displaying the relevant data in the user interface. Developers can easily skip the tedious process of writing the network-based codes using AsyncTask. This reduces the overall size of the source code and makes the repository easy-to-maintain and debug. This is the main reason that developers prefer Volley over AsyncTask.

Working of Async class
Image Source: Smashing Magazine

For instance, if we employ Asynctask to fetch an image and its corresponding description from a native JSON array created in server API. The data is fetched and displayed in the user interface, but now if the user rotates the screen and toggles to the landscape mode. The previous activity is cleared from the stack, and now the data needs to be fetched again. Since multiple network requests are being created for the same set of data, it leads to unnecessary congestion at the server and provides bad user experience, due to the latency.

Volley library utilises the cache memory of the device to improvise the App performance by reducing the memory requirement, congestion and the bandwidth of the remote server. Whenever a recurring data request is made by the user, rather than fetching the data from the server, Volley directly brings it from the cache saving resource and improves the overall user experience. However, Volley library is not compatible with large-sized download or high quality-streaming operations as it saves all responses in memory while parsing data.

Working of Volley Library
Image Source: Abhi Android

Volley comes with two default methods that allow us to synchronize pre and post execute activities also, namely the onPreExecute() and onPostExecute() method. The pre-requisites of a network request can be written in onPreExecute() method, such as fetching the parameters that are required to make the network request and the post-actions such as the setting of dialogs, alerts, progress bars, etc. These methods produce distinct and uniform networking codes and eliminate the need for writing BaseTask class for implementing and managing post operations.

Working of Volley Library:

Pre-requisites:

Step 1:
Open build.Gradle(Module: app) and add the following dependency and rebuild the project after syncing of the Gradle:
dependencies{
//…
implementation ‘com.android.volley:volley:1.0.0’
}

Step 2:
In AndroidManifest.xml add the internet permission:

Volley requests can be made by creating two classes in our Android Project:

  • RequestQueue: The network requests are stored in a queue in sequential order. A queue works on the FIFO strategy(First in first out). So the requests made first are attended first unless nay priority is specified.
  • A Request: Based on our requirements we need to pass the suitable parameters and call the specific API from the web server, for that we have to create valid network requests.

A network request can be of various types:

  • StringRequest: To retrieve the response body from the API as a String.
  • JsonArrayRequest: To fetch a JSON Array as a response from the server after the API call.
  • JsonObjectRequest: To send and receive JSON Object from the server via network requests.
  • ImageRequest: To receive an image from the server as a response.

Parameters that should be passed into the constructor to create a network request:

blog banner 1
  • First parameter The Request Method: The method of the created request should be specified, such as GET, POST, PUT and DELETE.
  • Second parameter URL: String of the URL of the required object.
  • Third parameter ResponseListener: Response Listener, whose callback method contains the response received from the API.
  • Fourth parameter ErrorListener: A Response.ErrorListener whose callback method will deal with any error generated while executing the network request.

Creating a Volley request:
The below shows a Volley string request for fetching the name, date of birth and phone number of a user by sending the username to the server.

private void getdata() {
final List senderList = new ArrayList<>();
StringRequest stringRequest=new StringRequest(com.android.volley.Request.Method.POST, sent, new Response.Listener() {
@Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);

                //traversing through all the object
                for (int i = 0; i < array.length(); i++)
                {
                    //getting person object from json array
                    JSONObject obj = array.getJSONObject(i);
                    //fetching the details one by one ,through column name
                    String name = obj.getString("Name");
                    String date = obj.getString("Date");
                     String  phone = obj.getString("Phone");
                    senderList.add(new Sender(name,date,phone));

}
//Set the adapter to display the data
startAdapter(senderList);
}
catch (JSONException e)
{
e.printStackTrace();
}

        } 
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

//in case of any error in the path, the error will get displayed as a toast.
Toast.makeText(getActivity(),”Couldn’t fetch data”,Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}
)
{
//a key value data structure is created for sending the parameters
protected Map getParams() throws AuthFailureError {
Mapparams=new HashMap<>();
params.put(“username”,uname);
return params;
}};
//the request is added to the RequestQueue class(MySingleton)
MySingleton.getInstance(getActivity()).addToRequestQueue(stringRequest);
}

Request Prioritisation
We all know that networking is real-time operation, therefore at any point of time, an urgent network request can be made by the user, at this moment, all the network request present in the queue needs to be withheld. Volley provides us extensible methods to set and get the network request priority so that it can be answered without any latency-setPriority() and getPriority().

Cancel Requests
If any already queued network request is not required further, Volley allows us to cancel the partially executed or non-executed network request by using the onStop() method. The most efficient way to cancel requests is to add a tag to the request and when the queued requests need to be cancelled, call the cancelAll() method. This will cancel all the network requests that possess the corresponding tag.

request.setTag(“TAG”);
requestQueue.cancelAll(“TAG”);

As soon as the cancelAll() method is invoked from the main thread, the residual responses will be dropped instantly.

Top Features of Volley Library in Android:

  • Volley allows us to create request queues and assign priorities.
  • We can block and revert unwanted requests.
  • Volley utilises the cache memory to reduce latency while making network requests.
  •  It is an abstract class for carrying out Basic HTTP operations in Android Studio.
  • It reduces space complexity and does auto memory management.
  • It allows a high degree of customisation by providing Custom RequestQueue.
  • It allows us to create a RequestQueue for scheduling API calls.
  • It offers a high degree of extensibility to the developers.

Top Advantages of using Volley:

  • Volley library possess efficient customisation abilities to allow the creation of application-specific requests.
  • The disk and memory caching paradigm followed by Volley is completely transparent so that developers understand the data flow.
  • Volley comes with the bundle of debugging and error tracing tools which allow easy testing and maintenance of the source code.
  • Volley nearly covers all the aspects of networking related to Android including image requests.
  • We can schedule network requests by using Volley, such that automated network request is run through the app and the data is updated sequentially in regular interval of time. This feature is used in applications used for weather forecasting applications or stock market management applications so that data is updated on a daily basis.
  • Even image requests can be scheduled using volley library.
  • Volley provides higher security as it can cancel, block or revert a specific request or a block of requests according to the developer commands.

To explore more about Android, click here.

By Vanshika Singolia