Android Bitmap Cache Bitmap Cache Using LRU Cache

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

LRU Cache

The following example code demonstrates a possible implementation of the LruCache class for caching images.

private LruCache<String, Bitmap> mMemoryCache;

Here string value is key for bitmap value.

// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;

mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
    @Override
    protected int sizeOf(String key, Bitmap bitmap) {
        // The cache size will be measured in kilobytes rather than
        // number of items.
        return bitmap.getByteCount() / 1024;
    }
};

For add bitmap to the memory cache

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }    
}

For get bitmap from memory cache

public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}

For loading bitmap into imageview just use getBitmapFromMemCache("Pass key").



Got any Android Question?