0

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.

Ali Akram
  • 4,803
  • 3
  • 29
  • 38

1 Answers1

0

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.

Enselic
  • 4,434
  • 2
  • 30
  • 42
  • I tried removing `/1024` from both places both, still not saving. – Ali Akram Oct 04 '19 at 07:13
  • by the way `/1024` is there in [Official Documentation](https://developer.android.com/topic/performance/graphics/cache-bitmap#kotlin). – Ali Akram Oct 04 '19 at 07:15
  • @AliAkram Please provide complete sample code, including the code where you add the bitmap and how you create the bitmap, and also what Android platform you run on. – Enselic Oct 04 '19 at 07:25
  • Your code works for me. But you did not provide a complete example. For example, I don't have R.drawable.placeholder. And just `cacheStock.get("11")` is pointless. What do you expect should happen here? Please provide a more complete example. And avoid things like `(Runtime.getRuntime().maxMemory() / 1024).toInt() / 8`. Use a fixed value instead. – Enselic Oct 05 '19 at 11:44
  • Try with something other than Bitamp, e.g. Integer, and make sizeOf return the value of the integer. – Enselic Oct 05 '19 at 11:52
  • 1
    The point I was missing or confusing was `LruCache` is persistent memory and I was expecting it to keep bitmap even after reopening app but i got to know that its only app level memory that destroy with app life cycle. – Ali Akram Oct 05 '19 at 14:15