Volley only caches images in memory, but I want the cache both on disk and memory

284 Views Asked by At

I'm using volley like this. The problem is, Volley in my case only caches images in the memory but not on the disk. If I force the my application, all caches will be removed from the memory. How can I have caches on both the memory and the disk?

public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache(getApplicationContext()));
        }
        return this.mImageLoader;
    }

holder.picture.setImageUrl(url, MyApplication.getInstance().getImageLoader());

Note: I had used DiskLruCache written by Jake Wharton and everything works fine but in this way, caches only exist on the disk. I want Volley to get the bitmap from the memory if exists, otherwise from the disk if exists, if there is no cache for the URL, make a network call.

1

There are 1 best solutions below

0
On

Volley first tries to find cache in LruBitmapCache, you may find related codes in ImageLoader.java

Bitmap cachedBitmap = mCache.getBitmap(cacheKey);
if (cachedBitmap != null) {
    // Return the cached bitmap.
    ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, null, null);
    imageListener.onResponse(container, true);
    return container;
}

Then Volley goes the same way as other http requests (that does not use ImageLoader). In short, a DiskLruCache is used by default. Volley uses CacheDispatcher to deal with cache on disk. The cache strategy is based on Cache-Control and/or other headers from server.

As far as I know, volley will by default cache all requests, despite no Cache-Control or related headers. However, caches will not be used if no such header exists.

If you do not want to change the logic of volley, you may consider supporting Cache from serverside.