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;
}
}
};
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:you should have to clear cache and download again when you got Exception . Check below function to clear cache when memory exceeds
Out of Memory Exception
is caused when bitmaps exceeds the virtual memory available, a good practice is the Recycle of bitmaps.Read more here
When should I recycle a bitmap using LRUCache?
a question answered by Mr. Mark Murphy.
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.