androidcachingbitmapandroid-lru-cache

Implementing LruCache for caching bitmap images


In my application I am fetching a feed from Internet. feed contains some text information and image. I have to store images in LruCache, for that I have referred Google developer website and implemented as shown in there. this implementation works fine. but since my application supports from api level 10, it show some error allocation cache size, I cant declare the size for cache sine I am using bitmap.getByteCount() it shows add @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1) notation, and when I open the application in android 2.3 application stops responding

Code

import android.support.v4.util.LruCache;

    private LruCache<String,Bitmap> mMemoryCache;

    onCreate(Bundle savedInstanceState){
       manageCache();
    }

    private void manageCache() {
            mMemoryCache = new LruCache<String, Bitmap>(mCacheSize) {
                @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    return bitmap.getByteCount() / 1024;
                }
            };
        }

how can I support for api level 10 also, is there any way ?


Solution

  • To calculate the in-memory size of the bitmap prior to API level 12 you may use this code:

    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    

    So the method sizeOf will look like this:

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
    @Override
    protected int sizeOf(String key, Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
            return bitmap.getByteCount();
        } else {
            return bitmap.getRowBytes() * bitmap.getHeight();
        }
    }
    

    P.S. you have to return a size of a bitmap in bytes, so you must not divide bitmap.getByteCount() by 1024.