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.
Putting a
Bitmapinto it fails whenvalue!!.byteCount / 1024evaluates to zero. If you put in a large enoughBitmap, it will work also with the current code.You need to make sure that
sizeOf()never returns0. One easy way to do that is to work with bytes instead of kilobytes. Just remove both of your/ 1024divisions and the code will work.