0

The following code should be caching image into the memory but every time I run it the cache always return null. What could be the issue? I have used the code as exactly as it is on the Android Developer website.

private lateinit var memoryCache: LruCache<String, Bitmap>

fun load(imageUrl: String, imageView: ImageView) {

    val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()

    val cacheSize = maxMemory / 8

    memoryCache = object : LruCache<String, Bitmap>(cacheSize) {

        override fun sizeOf(key: String, bitmap: Bitmap): Int {

            return bitmap.byteCount / 1024

        }
    }

    CoroutineScope(IO).launch {

        loadBitmap(imageUrl, imageView)

    }

}

suspend fun loadBitmap(imageUrl: String, imageView: ImageView) {

    val bitmap: Bitmap? = memoryCache[imageUrl]

    if (bitmap != null) {
        withContext(Dispatchers.Main) {
            imageView.setImageBitmap(bitmap)
        }
    } else {
        val url = URL(imageUrl)
        val image = BitmapFactory.decodeStream(url.openConnection().getInputStream())

        withContext(Dispatchers.Main) {
            imageView.setImageBitmap(image)
        }
        memoryCache.put(imageUrl, image)
    }
}
ronnieotieno
  • 134
  • 2
  • 11

0 Answers0