Retrieving Network Data with Volley

Intro

As with all things programming, there are multiple ways to accomplish sending HTTP requests.  So far, we have used the XMLPullParser to retrieve XML and RSS data and the DefaultHttpClient for other page content, like JSON.  Which technique we use is situation dependant and, many times, based on the experience of the developer.    

This lesson introduces you to the Volley library, which is part of the Android Open Source Project (AOSP).  Volley allows you to create a queue of network requests, resulting in more efficient use of available bandwith and system resources. It also lets you prioritize and cancel requests; a feature not available with the options we've explored to date.

For additional reading on Volley, the developer docs are great (as always): http://developer.android.com/training/volley/index.html

At the Google I/O developer conference in 2013, Ficus Kirkpatrick of Google gave a presentation of Volley, along with some samples. It's worth watching when you get a chance:

 

In addition to introducing you to Volley, this lesson also shows you how to import an external module into your app...an important skill to have any time you need to use a library not provided natively by the SDK.

Adding Volley to your app

Because Volley is not included in the default SDK, we must take a few steps to make it available to our app.  

1. Retrieve the Source Code

First, we must get the library from the AOSP.  The recommended method for retrieving the source code is through the git repository.  

On Linux and OSX systems: 

  1. on the command line, issue the following commands:
cd <target directory>
git clone https://android.googlesource.com/platform/frameworks/volley

On Windows Systems:

  1. Open the Git GUI program
  2. Select "Clone Existing Repository" 

  3. In "Source Location", enter the URL: 
  4. https://android.googlesource.com/platform/frameworks/volley
  5. In "Target Location" enter the directory where you want the Volley files stored.  (I prefer to place them in a subdirectory of the default AndroidStudioProjects directory.) 

  6. Click the "Clone" button. 

  7. When the clone is complete, close the Git GUI and verify that the files were downloaded

 

2. Import volley into Android Studio

The next step is to import the volley source into Android Studio so that it's available for our app to use.  Look closely at the downloaded files and you'll notice that it's actually an Android Studio project already! (the build.gradle file gave it away)  This makes our job much easier.

  1. Create a new Android Studio Project named VolleyExample. 
  2. In Android Studio, select File > New Module 

  3. From the bottom More Modules list, select "Import Existing Project" 

  4. Select the newly downloaded volley folder as the Source Directory.

  5. Once imported, you'll notice the volley module now shows in the Project display.

3. Add volley module to app

After the volley library has been imported, you must 

  1. Select File > Project Structure 
  2. In the dependencies tab of the app module, click on the '+' at the bottom of the window and select Module dependency 

  3. Select the volley module and click OK

  4. Click OK one more time to close the Project Structure window

Your app is now all set up and ready to use the Volley AOSP library!

Using Volley 

In order to use Volley, you must first create a Request Queue that will be used to store and process network requests:

RequestQueue queue = Volley.newRequestQueue(this);

Once you have a Queue in which to place requests, the next logical thing to create a Request to put in it.  There are several kinds of Requests, and you should choose the one that best fits your needs.  The most generic type of Request is the StringRequest.  As the name suggests, the StringRequest object is used to retrieve a String from a network resource.

The StringRequest constructor takes four arguments:

For example:

StringRequest stringRequest = new StringRequest( Request.Method.GET, siteUrl,

        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
               // handle response 
            }
        }, 

        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // handle error
            }    
        }
);

We have a Queue and a Request.  Now we just need to place the Request in the Queue:

queue.add(stringRequest);

Cancelling a Request

Once of the nice things about using Volley is the ability to cancel an in-flight request.  To do so, just call cancel() on the Request:

stringRequest.cancel();

Sometimes you want to cancel more than one network request.  One way to accomplish this is to keep a reference to each request and call cancel on all of them.  A simpler way is to use the built in Tag feature of Requests.  We can Tag each request, and then use that Tag as a reference later.

stringRequest.setTag(TAG);

Once our Requests are tagged, we can use the cancelAll method of the Request Queue to cancel several requests at once:

queue.cancelAll(TAG);

Other Request Types

JSON Requests

Another type of request is useful when we want to retrieve JSON data from the network.  The format is just like StringRequest.  There are two kinds of JSON requests: JSONObjectRequest and JSONArrayRequest.  Here's an example of the former: 

JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, siteUrl, null,
	new Response.Listener<JSONObject>() {
		@Override
		public void onResponse(JSONObject jsonObj) {
			// handle JSON response
		}
	}, new Response.ErrorListener() {

		@Override
		public void onErrorResponse(VolleyError error) {
			// handle error
		}
	}
);
queue.add(jsonObjRequest);

 

Image Request

Retrieving an image file from the network isn't any harder:

ImageRequest imgRequest = new ImageRequest(url,
    new Response.Listener<Bitmap>() {
        @Override
        public void onResponse(Bitmap bitmap) {
            // handle Bitmap image
        }
    }, 0, 0, null,
    new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            // handle error
        }
    });
// Access the RequestQueue through your singleton class.
queue.add(imgRequest);

Your Task

Now it's your turn!  Your task is to modify the JSONWeatherExample app from the previous lesson so that it uses Volley to retrieve the JSON feed.