0

I am able to insert bitmap into LruCache but fails to retrieve previous decoded image. i am having more than 100 images in my db. when i am deoding it my gc mmemory is increasing.so i am implementing this to reuse the decoded image.

protected void onCreate()
{
    LruCache<String, Bitmap> mMemoryCache;
    codeforLru_oncreate();
    aa1=getBitmapFromMemCache(String.valueOf(aa));
    if (aa1 != null) 
    {
      iv.setImageBitmap(aa1);
    } 
    else
    {
      aa1= decodeSampledBitmapFromResource(aa);
      addBitmapToMemoryCache(String.valueOf(aa), aa1);
      iv.setImageBitmap(aa1);
    }
}

Getting max available VM memory, exceeding this amount will throw an OutOfMemory exception. Stored in kilobytes as LruCache takes an int in its constructor.

public void codeforLru_oncreate() {

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    // Use 1/8th of the available memory for this memory cache.
    final int cacheSize = maxMemory / 64;
    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            //app.setFlagForMemoryAlloc(1);
            return bitmap.getByteCount() / 1024;
        }
    };

}
   // code for adding bitmap into cache memory
  public void addBitmapToMemoryCache(String key, Bitmap bitmap) 
    {
    if (getBitmapFromMemCache(key) == null) {

        mMemoryCache.put(key, bitmap);
    }
}



//code for get bitmap from cache memory
public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}

//decoding here......
public Bitmap decodeSampledBitmapFromResource(byte[] decodethis)
{
     return                BitmapFactory.decodeByteArray(decodethis,0,decodethis.length,option);
}  
Amulya Khare
  • 7,718
  • 2
  • 23
  • 38

0 Answers0