2

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

Amir
  • 652
  • 9
  • 19

3 Answers3

1

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

Santhosh
  • 1,867
  • 2
  • 16
  • 23
  • 2
    thanks for your response, but i change the line final int cacheSize = maxMemory / 8; to final int cacheSize = maxMemory; but nothing changed – Amir Feb 15 '14 at 14:04
0

This works for me:

final int memClass = ((ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
final int cacheSize =  1024 *  1024 *memClass ;
Amir
  • 652
  • 9
  • 19
0

your problem lies here

return (bitmap.getRowBytes() * bitmap.getHeight() * 4)/1024;

it should be

return (bitmap.getRowBytes() * bitmap.getHeight())/1024;
Olayinka
  • 2,813
  • 2
  • 25
  • 43