Android Volley, A Networking Library (Part 2)

by Mir Suhail

In the Part1 of this blog I provided an introduction to Volley, its working style and the reasons which accede the developers to use Volley over other networking options available. If you haven’t read that blog, I suggest you to go through that blog first before continuing with more coding stuff. You can find the link of the Part1 of topic here.

Before using Volley library in our project, we have to import it into the package. We can import Volley in several ways.

The core Volley library is developed in the open AOSP repository at frameworks/volley and contains main request dispatch pipeline as well as a set of commonly applicable utilities, available in the Volley “toolbox.” The easiest way to add Volley to your project is to clone the Volley repository and set it as a library project:

  1. Git clone the repository by typing the following at the command line:
    git clone https://android.googlesource.com/platform/frameworks/volley
  2. Import the downloaded source into your app project as an Android library module

There is a another way. You can add to the dependency section of the build.gradle file this line:

It’s a mirror copy of the official Google repository, regularly synced and updated. It’s probably the simplest and fastest way to get started. However, be aware, it’s an unofficial Maven repository, no guarantees and not backed by Google.

At a high level, we use Volley by creating a RequestQueue and passing it Request objects. TheRequestQueue manages worker threads for running the network operations, reading from and writing to the cache, and parsing responses. Requests do the parsing of raw responses and Volley takes care of dispatching parsed responses back to the main thread for delivery.

The Request constructor always takes as parameters the method type (GET, POST, etc.), the URL of the resource, and event listeners. Then, depending on the type of request, it may ask for some more variables.

In the following example, we create a RequestQueue object by invoking one of Volley’s convenience methods, Volley.newRequestQueue. This sets up aRequestQueue object, using default values defined by Volley.

final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first response string.
        mTextView.setText("Response is: "+ response.toString());
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

Note that the listener syntax is similar to AsyncTask.onPostExecute, it simply becomes onResponse. This isn’t a coincidence. The developers that worked on Volley purposefully made the library’s API similar to AsyncTask methods. This makes transition from using AsyncTask to Volley easier.

Volley comes in handy for implementing three very common request types:

  • StringRequest
  • ImageRequest
  • JsonRequest

Each of these classes extend the Result class that we used earlier. We already looked at the StringRequest in the previous example. Let’s see instead how a JsonRequest works.

As you can see, the type of result is already set toJSONObject. You can ask for a JSONArray too if you want, using a JsonArrayRequest instead of a JsonObjectRequest.

As before, the first parameter of the constructor is the HTTP method to use. You then provide URL to fetch JSON from. The third variable in the example above is null. This is fine as it indicates that no parameters will be posted along with the request. Finally, you have the listener to receive JSON response and an error listener. You can pass in null if you want to ignore errors.

Switching from a GET request to a POST request is simple. You need to change the Request.Method in the constructor of the request and override thegetParams method, returning a proper Map<String, String> containing the parameters of the request.

StringRequest postRequest = new StringRequest(Request.Method.POST, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        JSONObject jsonResponse = new JSONObject(response).getJSONObject("form");
                        String site = jsonResponse.getString("site"),
                                network = jsonResponse.getString("network");
                        System.out.println("Name: "+name+"\nDesig: "+desig);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            }
    ) {
        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String>  params = new HashMap<>();
            // the POST parameters:
            params.put("name", "Suhail");
            params.put("desig", "developer");
            return params;
        }
    };
    Volley.newRequestQueue(this).add(postRequest);
}

If you have to cancel all ongoing requests, add following code snippet to the onStop method of your activity:

@Override
protected void onStop() {
    super.onStop();
    mRequestQueue.cancelAll(new RequestQueue.RequestFilter() {
        @Override
        public boolean apply(Request<?> request) {
            return true; // -> always yes
        }
    });
}

Take care when canceling requests. If you are depending on your response handler to advance a state or kick off another process, you need to account for this. Again, the response handler will not be called.

So, this is how we make network calls using Volley library. You may have noticed how easy and simple this approach is.

To learn more and dig deep into Volley, follow the android official tutorial.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Mobile Research Apps

We have deep expertise in design and development of mobile research apps that work on both iOS and Android securely.

Contact us now

Popular Posts