Bitmap Cache Using LRU Cache

suggest change

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”).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents