LruCache not storing bitmap in kotlin Android

1.1k views Asked by At

I am simply trying to cache bitmap into LruCache HashMap by doing this:

private lateinit var cacheStock: LruCache<String, Bitmap>
private lateinit var cacheStock: LruCache<String, Bitmap>
var maxCacheSize: Int = (Runtime.getRuntime().maxMemory() / 1024).toInt() / 8

   //Default Max Cache Size
    var maxCacheSize: Int = MemoryUtils().getVMCacheSize() / 8

    cacheStock = object : LruCache<String, Bitmap>(maxCacheSize) {

        override fun sizeOf(key: String?, value: Bitmap): Int {
            //returns bytecount in a bitmap
            return value.getByteCount() / 1024;
        }
    }

    imageView.setImageResource(R.drawable.placeholder);

    var bitmapdrawable:BitmapDrawable;
    bitmapdrawable= imageView.drawable as BitmapDrawable;

    cacheStock.put("11",bitmapdrawable.bitmap);
    cacheStock.put("12",bitmapdrawable.bitmap);
    cacheStock.put("13",bitmapdrawable.bitmap);


    cacheStock.get("11");
    cacheStock.get("12");
    cacheStock.get("13");

But the cacheStock does not save key-value pairs in it. It always has size 0 even after putting a bitmap into it.I also want to know is LruCache a persistent memory ? Please suggest where I am making a mistake.

1

There are 1 answers

6
Enselic On

Putting a Bitmap into it fails when value!!.byteCount / 1024 evaluates to zero. If you put in a large enough Bitmap, it will work also with the current code.

You need to make sure that sizeOf() never returns 0. One easy way to do that is to work with bytes instead of kilobytes. Just remove both of your / 1024 divisions and the code will work.