2

I have used Memory LRU Caching for caching bitmaps in my android application.but after some of the bitmaps are loaded into LRU map app force closes saying out of memory exception. I have spent whole day behind this but yet not found the solution please anyone can help me out I am badly stuck in this problem.Thanks in advance.

HERE IS MY CODE

final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
final int cacheSize = maxMemory / 8;
bitmapHashMap = new LruCache<String, Bitmap>(cacheSize)
{
@SuppressLint("NewApi")
@Override
protected int sizeOf(String key, Bitmap value)
{
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB_MR2)
{
return value.getByteCount()/1024;
}
else
{
return (value.getRowBytes() * value.getHeight())/1024;
}
}
};
Ravi
  • 93
  • 3
  • 11

4 Answers4

2

If your app uses android:largeheap="true",

Never use Runtime.getRuntime().maxMemory() as you will most likely use more memory than availabe and OOM more often, instead use the memory class and calculate the size of the cache as follows:

    /** Default proportion of available heap to use for the cache */
    final int DEFAULT_CACHE_SIZE_PROPORTION = 8;

    ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    int memoryClass = manager.getMemoryClass();
    int memoryClassInKilobytes = memoryClass * 1024;
    int cacheSize = memoryClassInKilobytes / DEFAULT_CACHE_SIZE_PROPORTION;
    bitmapHashMap = new LruCache<String, Bitmap>(cacheSize)
petey
  • 16,151
  • 5
  • 59
  • 92
  • 1
    i have used the same but it is giving the same out of memory error is it because images are not recycled or what?? Lru is not performing these recycling things by default??? – Ravi Feb 21 '14 at 06:46
  • What is the value of DEFAULT_CACHE_SIZE_PROPORTION as I am unable to find any references to it. – Theo Feb 26 '14 at 11:50
  • what if your app doesn't use largeHeap="true"? – Adam Johns May 14 '14 at 14:16
  • check the bitmap being loaded and the stacktrace, it will usually tell you the memory limit and the attempt to allow the required memory needed at bOOM time. – petey May 14 '14 at 15:26
1

Out of Memory Exception is caused when bitmaps exceeds the virtual memory available, a good practice is the Recycle of bitmaps.

  bitmap.recycle();

Read more here

When should I recycle a bitmap using LRUCache?

a question answered by Mr. Mark Murphy.

Community
  • 1
  • 1
Jorgesys
  • 114,263
  • 22
  • 306
  • 247
  • 2
    Lru can't perform these recycling things by default on its own or what??? is it compulsory to perform these recycling manually in code??? – Ravi Feb 21 '14 at 06:49
0

Have you follow these guide ? http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html This is a good tutorial to know how to implement storage of bitmaps.

Substitut
  • 313
  • 1
  • 2
  • 8
  • yes i have referred the same document for memory caching but it is giving me out of memory error. Is it because images are not recycled or what? do i need to recycle these bitmaps in lru map manually?? – Ravi Feb 21 '14 at 06:00
  • You have to combine the usage of LRU Cache with a set of soffReference. SoftReference class will automtically delete bitmap instance before to have an out of memory exception. – Substitut Feb 21 '14 at 08:43
0

you should have to clear cache and download again when you got Exception . Check below function to clear cache when memory exceeds

    private Bitmap getBitmap(String url)
            {
     File f=fileCache.getFile(url);
     //from SD cache
    Bitmap b = decodeFile(f);
    if(b!=null)
        return b;

    //from web
    try {
        Bitmap bitmap=null;
      //  URL imageUrl = new URL(url);

        /***/

        HttpURLConnection conn = null;
        URL imageUrl = new URL(url);
        if (imageUrl.getProtocol().toLowerCase().equals("https")) {
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) imageUrl.openConnection();
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        } else {
            conn = (HttpURLConnection) imageUrl.openConnection();
        }
        /***/



       // HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex){
       ex.printStackTrace();
       if(ex instanceof OutOfMemoryError)
           memoryCache.clear();
       return null;
    }
}
Gopal Sharma
  • 290
  • 3
  • 14