performance - Android java.lang.OutOfMemoryError? -


04-25 08:19:10.111    2431-2603/com.example.francesco.guidedautorewithtabs e/art﹕ throwing outofmemoryerror "failed allocate 4194316 byte allocation 1983651 free bytes , 1937kb until oom" 04-25 08:19:10.114    2431-2603/com.example.francesco.guidedautorewithtabs e/androidruntime﹕ fatal exception: glthread 285 process: com.example.francesco.guidedautorewithtabs, pid: 2431 java.lang.outofmemoryerror: failed allocate 4194316 byte allocation 1983651 free bytes , 1937kb until oom         @ dalvik.system.vmruntime.newnonmovablearray(native method)         @ android.graphics.bitmap.nativecreate(native method)         @ android.graphics.bitmap.createbitmap(bitmap.java:817)         @ android.graphics.bitmap.createbitmap(bitmap.java:794)         @ android.graphics.bitmap.createbitmap(bitmap.java:761)         @ com.google.maps.api.android.lib6.gmm6.o.c.l.a(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.c.o.a(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.c.o.a(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.c.o.b(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.c.b.ak.a(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.c.b.as.a(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.x.a(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.l.a(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.l.b(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.cj.g(unknown source)         @ com.google.maps.api.android.lib6.gmm6.o.cj.run(unknown source) 

in android code have lot of images have displayed different fragment. several of stored in assets folder, other picked http request. reason implement image caching in order not go against java.lang.outofmemoryerror, nevertheless error seems persist. how can resolve problem? below implementation of image caching.

imageloader

public class imageloader { memorycache memorycache=new memorycache(); filecache filecache; private map<imageview, string> imageviews=collections.synchronizedmap(new weakhashmap<imageview, string>()); executorservice executorservice; private context context;  public imageloader(context context){     this.context=context;     filecache=new filecache(context);     executorservice=executors.newfixedthreadpool(5); }  final int stub_id= r.drawable.no_image; public void displayimage(string url, imageview imageview) {     imageviews.put(imageview, url);     bitmap bitmap=memorycache.get(url);     if(bitmap!=null)         imageview.setimagebitmap(bitmap);     else     {         queuephoto(url, imageview);         imageview.setimageresource(stub_id);     } }  private void queuephoto(string url, imageview imageview) {     phototoload p=new phototoload(url, imageview);     executorservice.submit(new photosloader(p)); }  private bitmap getbitmapfromasset(string strname) {     assetmanager assetmanager = context.getassets();     inputstream istr = null;     try {         istr = assetmanager.open(strname);     } catch (ioexception e) {         e.printstacktrace();     }     bitmap bitmap = bitmapfactory.decodestream(istr);     return bitmap; }  private bitmap getbitmap(string url) {     file f=filecache.getfile(url);      //from sd cache     bitmap b = decodefile(f);     if(b!=null)         return b;      //from assets     bitmap bm = getbitmapfromasset(url);      if(bm!=null)         return bm;      //from web     try {         bitmap bitmap=null;         url imageurl = new url(url);         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;     } }  //decodes image , scales reduce memory consumption private bitmap decodefile(file f){     try {         //decode image size         bitmapfactory.options o = new bitmapfactory.options();         o.injustdecodebounds = true;         bitmapfactory.decodestream(new fileinputstream(f),null,o);          //find correct scale value. should power of 2.         final int required_size=70;         int width_tmp=o.outwidth, height_tmp=o.outheight;         int scale=1;         while(true){             if(width_tmp/2<required_size || height_tmp/2<required_size)                 break;             width_tmp/=2;             height_tmp/=2;             scale*=2;         }          //decode insamplesize         bitmapfactory.options o2 = new bitmapfactory.options();         o2.insamplesize=scale;         return bitmapfactory.decodestream(new fileinputstream(f), null, o2);     } catch (filenotfoundexception e) {}     return null; }  //task queue private class phototoload {     public string url;     public imageview imageview;     public phototoload(string u, imageview i){         url=u;         imageview=i;     } }  class photosloader implements runnable {     phototoload phototoload;     photosloader(phototoload phototoload){         this.phototoload=phototoload;     }      @override     public void run() {         if(imageviewreused(phototoload))             return;         bitmap bmp=getbitmap(phototoload.url);         memorycache.put(phototoload.url, bmp);         if(imageviewreused(phototoload))             return;         bitmapdisplayer bd=new bitmapdisplayer(bmp, phototoload);         activity a=(activity)phototoload.imageview.getcontext();         a.runonuithread(bd);     } }  boolean imageviewreused(phototoload phototoload){     string tag=imageviews.get(phototoload.imageview);     if(tag==null || !tag.equals(phototoload.url))         return true;     return false; }  //used display bitmap in ui thread class bitmapdisplayer implements runnable {     bitmap bitmap;     phototoload phototoload;     public bitmapdisplayer(bitmap b, phototoload p){bitmap=b;phototoload=p;}     public void run()     {         if(imageviewreused(phototoload))             return;         if(bitmap!=null)             phototoload.imageview.setimagebitmap(bitmap);         else             phototoload.imageview.setimageresource(stub_id);     } }  public void clearcache() {     memorycache.clear();     filecache.clear(); } } 

filecache

public class filecache {  private file cachedir;  public filecache(context context){     //find dir save cached images     if (android.os.environment.getexternalstoragestate().equals(android.os.environment.media_mounted))         cachedir=new file(android.os.environment.getexternalstoragedirectory(),"ttimages_cache");     else         cachedir=context.getcachedir();     if(!cachedir.exists())         cachedir.mkdirs(); }  public file getfile(string url){     //i identify images hashcode. not perfect solution, demo.     string filename=string.valueof(url.hashcode());     //another possible solution (thanks grantland)     //string filename = urlencoder.encode(url);     file f = new file(cachedir, filename);     return f;  }  public void clear(){     file[] files=cachedir.listfiles();     if(files==null)         return;     for(file f:files)         f.delete(); }  } 

memorycache

public class memorycache {  private static final string tag = "memorycache"; private map<string, bitmap> cache=collections.synchronizedmap(         new linkedhashmap<string, bitmap>(10,1.5f,true));//last argument true lru ordering private long size=0;//current allocated size private long limit=1000000;//max memory in bytes  public memorycache(){     //use 25% of available heap size     setlimit(runtime.getruntime().maxmemory()/4); }  public void setlimit(long new_limit){     limit=new_limit;     log.i(tag, "memorycache use "+limit/1024./1024.+"mb"); }  public bitmap get(string id){     try{         if(!cache.containskey(id))             return null;         //nullpointerexception happen here http://code.google.com/p/osmdroid/issues/detail?id=78         return cache.get(id);     }catch(nullpointerexception ex){         ex.printstacktrace();         return null;     } }  public void put(string id, bitmap bitmap){     try{         if(cache.containskey(id))             size-=getsizeinbytes(cache.get(id));         cache.put(id, bitmap);         size+=getsizeinbytes(bitmap);         checksize();     }catch(throwable th){         th.printstacktrace();     } }  private void checksize() {     log.i(tag, "cache size="+size+" length="+cache.size());     if(size>limit){         iterator<entry<string, bitmap>> iter=cache.entryset().iterator();//least accessed item first 1 iterated         while(iter.hasnext()){             entry<string, bitmap> entry=iter.next();             size-=getsizeinbytes(entry.getvalue());             iter.remove();             if(size<=limit)                 break;         }         log.i(tag, "clean cache. new size "+cache.size());     } }  public void clear() {     try{         //nullpointerexception happen here http://code.google.com/p/osmdroid/issues/detail?id=78         cache.clear();         size=0;     }catch(nullpointerexception ex){         ex.printstacktrace();     } }  long getsizeinbytes(bitmap bitmap) {     if(bitmap==null)         return 0;     return bitmap.getrowbytes() * bitmap.getheight(); } } 

utils

public class utils { public static void copystream(inputstream is, outputstream os) {     final int buffer_size=1024;     try     {         byte[] bytes=new byte[buffer_size];         for(;;)         {             int count=is.read(bytes, 0, buffer_size);             if(count==-1)                 break;             os.write(bytes, 0, count);         }     }     catch(exception ex){} } } 

try may add tag in manifest file.

<application android:largeheap="true"> </application> 

it allocate large heap app


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -