Example using Androids lrucache

Viewed 48043

I need help understanding androids LruCache. I want to use to load images into my gridview in order make the loading/scrolling better. Can someone post an example code using LruCache please. Thanks in advance.

5 Answers

Utility Class to save and retrieve Bitmap from own Cache.

package com.roomco.android.utils;

import android.graphics.Bitmap;
import android.support.v4.util.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){

      MyCache.getInstance().getLru().put(key, bitmap);
  }

  public Bitmap retrieveBitmapFromCache(String key){

      Bitmap bitmap = (Bitmap)MyCache.getInstance().getLru().get(key);
      return bitmap;
  }

}

Usage:

//Save bitmap in cache
MyCache.getInstance().saveBitmapToCahche("your_key",bitmap);
// Get bitmap from cache
MyCache.getInstance().retrieveBitmapFromCache("your_key");
Related