How To Prevent Out Of Memory Error In Lru Caching Android
Solution 1:
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 */finalint 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)
Solution 2:
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.
Solution 3:
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.
Solution 4:
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 cacheBitmapb= decodeFile(f);
if(b!=null)
return b;
//from webtry {
Bitmap bitmap=null;
// URL imageUrl = new URL(url);/***/HttpURLConnectionconn=null;
URLimageUrl=newURL(url);
if (imageUrl.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnectionhttps= (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();
OutputStreamos=newFileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Throwable ex){
ex.printStackTrace();
if(ex instanceof OutOfMemoryError)
memoryCache.clear();
returnnull;
}
}
Post a Comment for "How To Prevent Out Of Memory Error In Lru Caching Android"