Skip to content

Instantly share code, notes, and snippets.

@ficusk
Created May 20, 2013 18:44
Show Gist options
  • Save ficusk/5614325 to your computer and use it in GitHub Desktop.
Save ficusk/5614325 to your computer and use it in GitHub Desktop.
package your.awesome.app;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import com.android.volley.toolbox.ImageLoader.ImageCache;
public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageCache {
public LruBitmapCache(int maxSize) {
super(maxSize);
}
@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);
}
}
@gitreadynow
Copy link

Could you indicate how to provided a correct maxSize value? I think it was indicated three screens worth? How is that calculated in Android? Thanks

@ArnaudCourbiere
Copy link

It would be something like this:

public int getCacheSize() {
    final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
    final int screenWidth = displayMetrics.widthPixels;
    final int screenHeight = displayMetrics.heightPixels;
    final in screenBytes = screenWidth * screenHeight * 4; // 4 bytes per pixel

    return screenBytes * 3;
}

@c0ming
Copy link

c0ming commented Nov 21, 2013

maxSize for caches that do not override sizeOf(K, V), this is the maximum number of entries in the cache. http://developer.android.com/reference/android/util/LruCache.html#LruCache(int) or int maxSize = (int) (Runtime.getRuntime().maxMemory() / 1024 / 8);

@Sottti
Copy link

Sottti commented Sep 9, 2014

@ArnaudCourbiere

You can take a look here at the code of the Google way of do this:
http://developer.android.com/training/volley/request.html

After all I think it depends on how you use volley. It makes sense on apps like Instagram or Google Play Store where you have the screen full of images. If you use Volley for request images but you have 1 or 2 images in each activity and they are not really loaded heavily... I have no idea how to work on this cache image stuff. Probably a few MB is enough.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment