Volley will automatically pull the bitmap from the cache when triggering an image request, provided you supplied the ImageLoader
you created with a valid ImageCache
object:
mImageLoader = new ImageLoader(mRequestQueue, new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap> mMemCache = new LruCache<String, Bitmap>(CACHE_SIZE);
@Override
public Bitmap getBitmap(String url) {
return mMemCache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
mMemCache.put(url, bitmap);
}
});
Then, to load images, use the ImageLoader
you created:
/**
* Performs a request to load an image from a given url.
* @param url the url to load the image from.
* @param listener the listener which will receive a call once the image load finishes (either with success or failure). The listener is called on the UI thread.
* @param maxWidth the max width (in pixels) of the requested image. The returned bitmap will not exceed this width. Use 0 for unlimited
* @param maxHeight the max height (in pixels) of the requested image. The returned bitmap will not exceed this height. Use 0 for unlimited.
* @return an ImageContainer object which can be used to access the bitmap once the request has completed, or to cancel the request before it completes.
*/
public ImageLoader.ImageContainer loadImageFromUrl(final String url, final ImageRequestListener listener, int maxWidth, int maxHeight) {
if (url == null || Uri.parse(url) == null || Uri.parse(url).getHost() == null) {
Logger.e("VolleyManager: loadImageFromUrl: invalid url " + url);
listener.onImageLoadFailed();
return null;
}
return mImageLoader.get(url, new ImageLoader.ImageListener() {
@Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
if (listener != null && response.getBitmap() != null) {
listener.onImageLoadComplete(response.getBitmap());
} else if (listener != null) {
listener.onImageLoadFailed(;
}
}
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
listener.onImageLoadFailed();
}
}
}, maxWidth, maxHeight);