Android TutorialsNo Comments

Andrologo.png
259 views.

Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Volley is available on GitHub.

Volley offers the following benefits:

Automatic scheduling of network requests.
Multiple concurrent network connections.
Transparent disk and memory response caching with standard HTTP cache coherence.
Support for request prioritization.
Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
Ease of customization, for example, for retry and backoff.
Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
Debugging and tracing tools.
Volley excels at RPC-type operations used to populate a UI, such as fetching a page of search results as structured data. It integrates easily with any protocol and comes out of the box with support for raw strings, images, and JSON. By providing built-in support for the features you need, Volley frees you from writing boilerplate code and allows you to concentrate on the logic that is specific to your app.

Volley is not suitable for large download or streaming operations, since Volley holds all responses in memory during parsing. For large download operations, consider using an alternative like DownloadManager.

The core Volley library is developed on GitHub and contains the 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 add the following dependency to your app’s build.gradle file:

You can also clone the Volley repository and set it as a library project:
Git clone the repository by typing the following at the command line:
git clone https://github.com/google/volley
Import the downloaded source into your app project as an Android library module as described in Create an Android Library.
Lessons
Sending a Simple Request
At a high level, you use Volley by creating a RequestQueue and passing it Request objects. The RequestQueue 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 the parsed response back to the main thread for delivery.

This lesson describes how to send a request using the Volley.newRequestQueue convenience method, which sets up a RequestQueue for you. See the next lesson, Setting Up a RequestQueue, for information on how to set up a RequestQueue yourself.

This lesson also describes how to add a request to a RequestQueue and cancel a request.

Add the INTERNET Permission
To use Volley, you must add the android.permission.INTERNET permission to your app’s manifest. Without this, your app won’t be able to connect to the network.

Use newRequestQueue
Volley provides a convenience method Volley.newRequestQueue that sets up a RequestQueue for you, using default values, and starts the queue. For example:

Volley always delivers parsed responses on the main thread. Running on the main thread is convenient for populating UI controls with received data, as you can freely modify UI controls directly from your response handler, but it’s especially critical to many of the important semantics provided by the library, particularly related to canceling requests.

See Setting Up a RequestQueue for a description of how to set up a RequestQueue yourself, instead of using the Volley.newRequestQueue convenience method.

Send a Request
To send a request, you simply construct one and add it to the RequestQueue with add(), as shown above. Once you add the request it moves through the pipeline, gets serviced, and has its raw response parsed and delivered.

When you call add(), Volley runs one cache processing thread and a pool of network dispatch threads. When you add a request to the queue, it is picked up by the cache thread and triaged: if the request can be serviced from cache, the cached response is parsed on the cache thread and the parsed response is delivered on the main thread. If the request cannot be serviced from cache, it is placed on the network queue. The first available network thread takes the request from the queue, performs the HTTP transaction, parses the response on the worker thread, writes the response to cache, and posts the parsed response back to the main thread for delivery.

Note that expensive operations like blocking I/O and parsing/decoding are done on worker threads. You can add a request from any thread, but responses are always delivered on the main thread.

Figure 1 illustrates the life of a request:

volley-request

Cancel a Request
To cancel a request, call cancel() on your Request object. Once cancelled, Volley guarantees that your response handler will never be called. What this means in practice is that you can cancel all of your pending requests in your activity’s onStop() method and you don’t have to litter your response handlers with checks for getActivity() == null, whether onSaveInstanceState() has been called already, or other defensive boilerplate.

To take advantage of this behavior, you would typically have to track all in-flight requests in order to be able to cancel them at the appropriate time. There is an easier way: you can associate a tag object with each request. You can then use this tag to provide a scope of requests to cancel. For example, you can tag all of your requests with the Activity they are being made on behalf of, and call requestQueue.cancelAll(this) from onStop(). Similarly, you could tag all thumbnail image requests in a ViewPager tab with their respective tabs and cancel on swipe to make sure that the new tab isn’t being held up by requests from another one.

Here is an example that uses a string value for the tag:

Define your tag and add it to your requests.

In your activity’s onStop() method, cancel all requests that have this tag.

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.
Setting Up a RequestQueue
The above showed you how to use the convenience method Volley.newRequestQueue to set up a RequestQueue, taking advantage of Volley’s default behaviors. This  walks you through the explicit steps of creating a RequestQueue, to allow you to supply your own custom behavior.

This lesson also describes the recommended practice of creating a RequestQueue as a singleton, which makes the RequestQueue last the lifetime of your app.

Set Up a Network and Cache
A RequestQueue needs two things to do its job: a network to perform transport of the requests, and a cache to handle caching. There are standard implementations of these available in the Volley toolbox: DiskBasedCache provides a one-file-per-response cache with an in-memory index, and BasicNetwork provides a network transport based on your preferred HTTP client.

BasicNetwork is Volley’s default network implementation. A BasicNetwork must be initialized with the HTTP client your app is using to connect to the network. Typically this is an HttpURLConnection.

This snippet shows you the steps involved in setting up a RequestQueue:

If you just need to make a one-time request and don’t want to leave the thread pool around, you can create the RequestQueue wherever you need it and call stop() on the RequestQueue once your response or error has come back, using the Volley.newRequestQueue() method described in Sending a Simple Request. But the more common use case is to create the RequestQueue as a singleton to keep it running for the lifetime of your app, as described in the next section.

Use a Singleton Pattern
If your application makes constant use of the network, it’s probably most efficient to set up a single instance of RequestQueue that will last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates RequestQueue and other Volley functionality. Another approach is to subclass Application and set up the RequestQueue in Application.onCreate(). But this approach is discouraged; a static singleton can provide the same functionality in a more modular way.

A key concept is that the RequestQueue must be instantiated with the Application context, not an Activity context. This ensures that the RequestQueue will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).

Here is an example of a singleton class that provides RequestQueue and ImageLoader functionality:

Here are some examples of performing RequestQueue operations using the singleton class:

Making a Standard Request

This  describes how to use the common request types that Volley supports:

StringRequest. Specify a URL and receive a raw string in response. See Setting Up a Request Queue for an example.
JsonObjectRequest and JsonArrayRequest (both subclasses of JsonRequest). Specify a URL and get a JSON object or array (respectively) in response.
If your expected response is one of these types, you probably don’t have to implement a custom request. This lesson describes how to use these standard request types. For information on how to implement your own custom request, see Implementing a Custom Request.

Request JSON

Volley provides the following classes for JSON requests:

JsonArrayRequest—A request for retrieving a JSONArray response body at a given URL.
JsonObjectRequest—A request for retrieving a JSONObject response body at a given URL, allowing for an optional JSONObject to be passed in as part of the request body.
Both classes are based on the common base class JsonRequest. You use them following the same basic pattern you use for other types of requests. For example, this snippet fetches a JSON feed and displays it as text in the UI:

Implementing a Custom Request

This  describes how to implement your own custom request types, for types that don’t have out-of-the-box Volley support.

Write a Custom Request
Most requests have ready-to-use implementations in the toolbox; if your response is a string, image, or JSON, you probably won’t need to implement a custom Request.
For cases where you do need to implement a custom request, this is all you need to do:

Extend the Request<T> class, where <T> represents the type of parsed response the request expects. So if your parsed response is a string, for example, create your custom request by extending Request<String>. See the Volley toolbox classes StringRequest and ImageRequest for examples of extending Request<T>.
Implement the abstract methods parseNetworkResponse() and deliverResponse(), described in more detail below.
parseNetworkResponse
A Response encapsulates a parsed response for delivery, for a given type (such as string, image, or JSON). Here is a sample implementation of parseNetworkResponse():

Note the following:

parseNetworkResponse() takes as its parameter a NetworkResponse, which contains the response payload as a byte[], HTTP status code, and response headers.
Your implementation must return a Response<T>, which contains your typed response object and cache metadata or an error, such as in the case of a parse failure.
If your protocol has non-standard cache semantics, you can build a Cache.Entry yourself, but most requests are fine with something like this:

Volley calls parseNetworkResponse() from a worker thread. This ensures that expensive parsing operations, such as decoding a JPEG into a Bitmap, don’t block the UI thread.

deliverResponse
Volley calls you back on the main thread with the object you returned in parseNetworkResponse(). Most requests invoke a callback interface here, for example:

Example: GsonRequest
Gson is a library for converting Java objects to and from JSON using reflection. You can define Java objects that have the same names as their corresponding JSON keys, pass Gson the class object, and Gson will fill in the fields for you. Here’s a complete implementation of a Volley request that uses Gson for parsing:

 

Be the first to post a comment.

Add a comment