It’s a common requirement when we have to save our Images/Bitmaps into the cache in Android. For this purpose, we can use LruCache. Although most of the time while loading images from the server, we use some third party image caching libraries like Picasso, Glide, or Fresco. But if the image is not coming from a remote URL like loading from local storage, we can use the following class which is using LruCache to save and load/retrieve bitmap from the cache in Kotlin.
Following is Kotlin code, but here you can also find Java code on LruCache.
Utility Class to Save and load Image from Cache Using LruCache in Kotlin
Just create a file in your project with the name MyCache.kt
and copy and paste the following code in that file.
import android.graphics.Bitmap
import androidx.collection.LruCache
class MyCache private constructor() {
private object HOLDER {
val INSTANCE = MyCache()
}
companion object {
val instance: MyCache by lazy { HOLDER.INSTANCE }
}
val lru: LruCache<Any, Any>
init {
lru = LruCache(1024)
}
fun saveBitmapToCahche(key: String, bitmap: Bitmap) {
try {
MyCache.instance.lru.put(key, bitmap)
} catch (e: Exception) {
}
}
fun retrieveBitmapFromCache(key: String): Bitmap? {
try {
return MyCache.instance.lru.get(key) as Bitmap?
} catch (e: Exception) {
}
return null
}
}
How to Use MyCache Class?
As you can see in the above code, this class is a singleton class and contains 2 methods. First is saveBitmapToCahche(key: String, bitmap: Bitmap)
. It takes 2 parameters, actual bitmap to save, and the key identifying your bitmap. The second method is retrieveBitmapFromCache(key: String)
. Here we need to pass the same key to retrieve the same Bitmap again from the cache. Call these methods in the following way.
Save Bitmap in Cache
MyCache.instance.saveBitmapToCahche("bitmap1", YOUR_BITMAP_OBJECT)
Retrieve Bitmap from Cache
MyCache.instance.retrieveBitmapFromCache("bitmap1")
That’s it. Enjoy 🙂
Don’t forget to visit our Coding Articles & Tutorials Knowledge Base for other helping articles.