page.title=Making a Standard Request trainingnavtop=true @jd:body

This lesson teaches you to

  1. Request an Image
  2. Request JSON

Video

Volley: Easy, Fast Networking for Android

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

If your expected response is one of these types, you probably won'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 an Image

Volley offers the following classes for requesting images. These classes layer on top of each other to offer different levels of support for processing images:

Use ImageRequest

Here is an example of using {@code ImageRequest}. It retrieves the image specified by the URL and displays it in the app. Note that this snippet interacts with the {@code RequestQueue} through a singleton class (see Setting Up a RequestQueue for more discussion of this topic):

ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
...

// Retrieves an image specified by the URL, displays it in the UI.
ImageRequest request = new ImageRequest(url,
    new Response.Listener() {
        @Override
        public void onResponse(Bitmap bitmap) {
            mImageView.setImageBitmap(bitmap);
        }
    }, 0, 0, null,
    new Response.ErrorListener() {
        public void onErrorResponse(VolleyError error) {
            mImageView.setImageResource(R.drawable.image_load_error);
        }
    });
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(request);

Use ImageLoader and NetworkImageView

You can use {@code ImageLoader} and {@code NetworkImageView} in concert to efficiently manage the display of multiple images, such as in a {@link android.widget.ListView}. In your layout XML file, you use {@code NetworkImageView} in much the same way you would use {@link android.widget.ImageView}, for example:

<com.android.volley.toolbox.NetworkImageView
        android:id="@+id/networkImageView"
        android:layout_width="150dp"
        android:layout_height="170dp"
        android:layout_centerHorizontal="true" />

You can use {@code ImageLoader} by itself to display an image, for example:

ImageLoader mImageLoader;
ImageView mImageView;
// The URL for the image that is being loaded.
private static final String IMAGE_URL =
    "http://developer.android.com/images/training/system-ui.png";
...
mImageView = (ImageView) findViewById(R.id.regularImageView);

// Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader();
mImageLoader.get(IMAGE_URL, ImageLoader.getImageListener(mImageView,
         R.drawable.def_image, R.drawable.err_image));

However, {@code NetworkImageView} can do this for you if all you're doing is populating an {@link android.widget.ImageView}. For example:

ImageLoader mImageLoader;
NetworkImageView mNetworkImageView;
private static final String IMAGE_URL =
    "http://developer.android.com/images/training/system-ui.png";
...

// Get the NetworkImageView that will display the image.
mNetworkImageView = (NetworkImageView) findViewById(R.id.networkImageView);

// Get the ImageLoader through your singleton class.
mImageLoader = MySingleton.getInstance(this).getImageLoader();

// Set the URL of the image that should be loaded into this view, and
// specify the ImageLoader that will be used to make the request.
mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);

The above snippets access the {@code RequestQueue} and the {@code ImageLoader} through a singleton class, as described in Setting Up a RequestQueue. This approach ensures that your app creates single instances of these classes that last the lifetime of your app. The reason that this is important for {@code ImageLoader} (the helper class that handles loading and caching images) is that the main function of the in-memory cache is to allow for flickerless rotation. Using a singleton pattern allows the bitmap cache to outlive the activity. If instead you create the {@code ImageLoader} in an activity, the {@code ImageLoader} would be recreated along with the activity every time the user rotates the device. This would cause flickering.

Example LRU cache

The Volley toolbox provides a standard cache implementation via the {@code DiskBasedCache} class. This class caches files directly onto the hard disk in the specified directory. But to use {@code ImageLoader}, you should provide a custom in-memory LRU bitmap cache that implements the {@code ImageLoader.ImageCache} interface. You may want to set up your cache as a singleton; for more discussion of this topic, see Setting Up a RequestQueue.

Here is a sample implementation for an in-memory {@code LruBitmapCache} class. It extends the {@link android.support.v4.util.LruCache} class and implements the {@code ImageLoader.ImageCache} interface:

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.DisplayMetrics;
import com.android.volley.toolbox.ImageLoader.ImageCache;

public class LruBitmapCache extends LruCache<String, Bitmap>
        implements ImageCache {

    public LruBitmapCache(int maxSize) {
        super(maxSize);
    }

    public LruBitmapCache(Context ctx) {
        this(getCacheSize(ctx));
    }

    @Override
    protected int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }

    @Override
    public Bitmap getBitmap(String url) {
        return get(url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        put(url, bitmap);
    }

    // Returns a cache size equal to approximately three screens worth of images.
    public static int getCacheSize(Context ctx) {
        final DisplayMetrics displayMetrics = ctx.getResources().
                getDisplayMetrics();
        final int screenWidth = displayMetrics.widthPixels;
        final int screenHeight = displayMetrics.heightPixels;
        // 4 bytes per pixel
        final int screenBytes = screenWidth * screenHeight * 4;

        return screenBytes * 3;
    }
}

Here is an example of how to instantiate an {@code ImageLoader} to use this cache:

RequestQueue mRequestQueue; // assume this exists.
ImageLoader mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(
            LruBitmapCache.getCacheSize()));

Request JSON

Volley provides the following classes for JSON requests:

Both classes are based on the common base class {@code 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:

TextView mTxtDisplay;
ImageView mImageView;
mTxtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://my-json-feed";

JsonObjectRequest jsObjRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Response.Listener() {

    @Override
    public void onResponse(JSONObject response) {
        mTxtDisplay.setText("Response: " + response.toString());
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub

    }
});

// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
For an example of implementing a custom JSON request based on Gson, see the next lesson, Implementing a Custom Request.