androidmemory-leaksout-of-memorybitmapimageandroid-lru-cache

android: LruCache return null


I am new to LruCache in android and i want to put and get bitmap images (JPEG) on this cache to prevent memory errors and memory exception, so i can't understand why my code does not work. here is my code:

ImageView imageview = (ImageView)findViewById(R.id.imageView1);
Bitmap b = BitmapFactory.decodeFile(imagePath); 
mMemoryCache.put("mykey", b);
b = mMemoryCache.get("mykey");
imageview.setImageBitmap(b);

and this is my LruCache code:

import android.support.v4.util.LruCache;
...
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return (bitmap.getRowBytes() * bitmap.getHeight() * 4)/1024;
        }
    };
}

i don't know why is not working :( thanks


Solution

  • It was because of low cache Size for data to store so ..check it by giving final int cacheSize = maxMemory; or by sufficient cache size