How to Save and Load Bitmap from Cache using LruCache in Java Android

During mobile Apps development, it’s a good practice to save images in the cache for next time fast loading. Most of the time we use Image caching libraries like Fresco, Picasso, or Glide for caching when we load images from a remote URL. But we can also use Android’s native LruChache class for this purpose. In this article, a utility class is shared through which you can directly save and load Bitmap from the cache using LruCache in Java Android.

Following is the Java code but here you can find Kotlin code to Save & retrieve Bitmap From Cache using LruCache.

Utility Class to Save and load Image from Cache Using LruCache in Java

Create a java file in your project with the name MyCache.java and paste the following code.

import android.graphics.Bitmap;
import androidx.collection.LruCache;

public class MyCache {

private static MyCache instance;
private LruCache<Object, Object> lru;

private MyCache() {

lru = new LruCache<Object, Object>(1024);

}

public static MyCache getInstance() {

if (instance == null) {
instance = new MyCache();
}
return instance;

}

public LruCache<Object, Object> getLru() {
return lru;
}

public void saveBitmapToCahche(String key, Bitmap bitmap){

try {
MyCache.getInstance().getLru().put(key, bitmap);
}catch (Exception e){}
}

public Bitmap retrieveBitmapFromCache(String key){

try {
Bitmap bitmap = (Bitmap) MyCache.getInstance().getLru().get(key);
return bitmap;
}catch (Exception e){}
return null;
}

}

How to Call the Above MyCache Class Methods?

It’s a singleton class and you can get its instance by calling MyCache.getInstance() method. You can see 2 methods in this class. First is saveBitmapToCahche(String key, Bitmap bitmap), which takes 2 parameters, your Bitmap, and the key to save bitmap against your specified identifier. The second method is retrieveBitmapFromCache(String key), it takes the same key as the parameter to return your saved Bitmap from the cache. Use these methods in the following way.

Save Bitmap in Cache

MyCache.getInstance().saveBitmapToCahche("bitmap1", YOUR_BITMAP_OBJECT);

Get Bitmap from Cache

Bitmap bitmap = MyCache.getInstance().retrieveBitmapFromCache("bitmap1");

That’s it. This is how you can save and load Bitmap from the cache using LruCache in Java Android.

Please visit our Coding Articles List for other helping tutorials.

Please share this post:
Native Mobile Application Developer (Android + IOS) having experience in Java, Swift, Kotlin, Objective C, Unity, C#, C/C++, NODE JS & PHP.

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

%d bloggers like this: