Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Aug 2, 2013

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

This comment has been minimized.

Copy link

commented Aug 22, 2013

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

This comment has been minimized.

Copy link

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

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.