java - How to display an image from a url in android -


i working on first android application. need display image url in app. tried in following way:

mainactivity file:

public class mainviewactivity extends activity {  @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main_view);       int loader = r.drawable.loader;          // imageview show         imageview image = (imageview) findviewbyid(r.id.image);          // image url         string image_url = "http://..../landing.png";          // imageloader class instance         imageloader imgloader = new imageloader(getapplicationcontext());           imgloader.displayimage(image_url, loader, image); }  @override public boolean oncreateoptionsmenu(menu menu) {     // inflate menu; adds items action bar if present.     getmenuinflater().inflate(r.menu.activity_main_view, menu);     return true; } 

}

here getting error in line int loader = r.drawable.loader;

the class file are:

filecache.java

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(),"tempimages");     else         cachedir=context.getcachedir();     if(!cachedir.exists())         cachedir.mkdirs(); }  public file getfile(string url){     string filename=string.valueof(url.hashcode());     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(); } 

}

imageloader.java

public class imageloader {  memorycache memorycache=new memorycache(); filecache filecache; private map<imageview, string> imageviews=collections.synchronizedmap(new weakhashmap<imageview, string>()); executorservice executorservice;  public imageloader(context context){     filecache=new filecache(context);     executorservice=executors.newfixedthreadpool(5); }  int stub_id = r.drawable.ic_launcher; public void displayimage(string url, int loader, imageview imageview) {     stub_id = loader;     imageviews.put(imageview, url);     bitmap bitmap=memorycache.get(url);     if(bitmap!=null)         imageview.setimagebitmap(bitmap);     else     {         queuephoto(url, imageview);         imageview.setimageresource(loader);     } }  private void queuephoto(string url, imageview imageview) {     phototoload p=new phototoload(url, imageview);     executorservice.submit(new photosloader(p)); }  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 = (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 (exception ex){        ex.printstacktrace();        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(); }  } 

memorycache.java

public class memorycache { private map<string, softreference<bitmap>> cache=collections.synchronizedmap(new     hashmap<string, softreference<bitmap>>());  public bitmap get(string id){     if(!cache.containskey(id))         return null;     softreference<bitmap> ref=cache.get(id);     return ref.get(); }  public void put(string id, bitmap bitmap){     cache.put(id, new softreference<bitmap>(bitmap)); }  public void clear() {     cache.clear(); } } 

utils.java

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){} } } 

please fix error , see if there problem in code. have set required permissions in manifest file.

hi hope answer alot designed project download image url , store in cache memory , can use particular image project best if have doubt in project comment me explain each , every step in project... best...

public class mainactivity extends activity {  private imageview button; private bitmapfactory.options mbitmapoptions; private bitmap mbitmap; private textview mtime; private progressbar bar; private lrucache<string, bitmap> mmemorycache; private seekbar seekbar; private button change;  @suppresslint("newapi") @targetapi(build.version_codes.honeycomb_mr1) @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.main);     button = (imageview) findviewbyid(r.id.logo);     mtime = (textview) findviewbyid(r.id.time);     bar = (progressbar) findviewbyid(r.id.bar);     seekbar = (seekbar) findviewbyid(r.id.seekbar);     change = (button) findviewbyid(r.id.change);     mbitmapoptions = new bitmapfactory.options();     mbitmapoptions.injustdecodebounds = true;     bitmapfactory.decoderesource(getresources(), r.drawable.ic_launcher,             mbitmapoptions);     mbitmap = bitmap.createbitmap(mbitmapoptions.outwidth,             mbitmapoptions.outheight, config.argb_8888);     mbitmapoptions.injustdecodebounds = false;     mbitmapoptions.inbitmap = mbitmap;     mbitmapoptions.insamplesize = 1;     bitmapfactory.decoderesource(getresources(), r.drawable.ic_launcher,             mbitmapoptions);     button.setimagebitmap(mbitmap);          // use 1/8th of available memory memory cache.     final int cachesize = 20 * 1024 * 1024;     mmemorycache = new lrucache<string, bitmap>(cachesize) {         @targetapi(build.version_codes.honeycomb_mr1)         @override         protected int sizeof(string key, bitmap bitmap) {             // cache size measured in kilobytes rather             // number of items.             return bitmap.getbytecount();         }     };     int = 0;     system.out.println(mmemorycache.size());     system.out.println(mmemorycache.evictioncount());     bar.setmax(images.imagethumburls.length - 1);     seekbar.setmax(images.imagethumburls.length - 1);     bar.setprogress(0);     seekbar.setprogress(0);     (string string : images.imageurls) {         string position = string.valueof(i);         bitmapworkertask task = new bitmapworkertask(position);         task.executeonexecutor(asynctask.serial_executor, string);                   i++;     }     seekbar.setonseekbarchangelistener(new onseekbarchangelistener() {          @override         public void onstoptrackingtouch(seekbar seekbar) {         }          @override         public void onstarttrackingtouch(seekbar seekbar) {          }          @override         public void onprogresschanged(seekbar seekbar, int progress,                 boolean fromuser) {             if (images.imageurls.length > progress) {                 if (getbitmapfrommemcache(string.valueof(progress)) != null) {                     button.setimagebitmap(getbitmapfrommemcache(string                             .valueof(progress)));                 } else {                     // bitmapworkertask task = new                     // bitmapworkertask(string.valueof(progress));                     // task.executeonexecutor(asynctask.thread_pool_executor,images.imageurls[progress]);                 }             }          }     });     change.setonclicklistener(new onclicklistener() {          @override         public void onclick(view v) {             mmemorycache.evictall();             system.out.println(mmemorycache.size());             system.out.println(mmemorycache.evictioncount());             bar.setmax(images.imageurls.length - 1);             seekbar.setmax(images.imagethumburls.length - 1);             bar.setprogress(0);             seekbar.setprogress(0);             int = 0;                                           (string string : images.imageurls) {                 string position = string.valueof(i);                 bitmapworkertask task = new bitmapworkertask(position);                 task.executeonexecutor(asynctask.serial_executor, string);                                   i++;             }          }     }); }  @suppresslint("newapi") public void addbitmaptomemorycache(string position, bitmap bitmap) {     if (getbitmapfrommemcache(position) == null) {         mmemorycache.put(position, bitmap);     } }  public void loadbitmap(int resid, imageview imageview) {     final string imagekey = string.valueof(resid);      final bitmap bitmap = getbitmapfrommemcache(imagekey);     if (bitmap != null) {         button.setimagebitmap(bitmap);     } else {         button.setimageresource(r.drawable.ic_launcher);     } }  @suppresslint("newapi") public bitmap getbitmapfrommemcache(string imagekey) {     return mmemorycache.get(imagekey); }  class bitmapworkertask extends asynctask<string, void, bitmap> {     private string position = null;      // decode image in background.     public bitmapworkertask(string position) {         this.position = position;     }      @override     protected bitmap doinbackground(string... params) {         url url;         try {             url = new url(params[0]);             httpurlconnection connection = (httpurlconnection) url                     .openconnection();             connection.setconnecttimeout(200);             connection.setreadtimeout(1000);             int v = connection.getcontentlength() > 0 ? connection                     .getcontentlength() : 0;             if (v > 0) {                                     inputstream in = new bufferedinputstream(                         connection.getinputstream(), 32 * 1024);                 return decodesampledbitmapfromresource(in, 1000, 1000);             }         } catch (malformedurlexception e) {             //e.printstacktrace();         } catch (ioexception e) {             //e.printstacktrace();         }          return null;     }      @override     protected void onpostexecute(bitmap result) {         if (result != null) {             addbitmaptomemorycache(position, result);             // button.setimagebitmap(getbitmapfrommemcache(position));             mtime.settext(position);             bar.setprogress(integer.parseint(position));       //                system.out.println(result);         }     } }  public bitmap decodesampledbitmapfromresource(inputstream in, int reqwidth,         int reqheight) throws ioexception {      // first decode injustdecodebounds=true check dimensions     final bitmapfactory.options options = new bitmapfactory.options();     options.injustdecodebounds = true;     in.mark(in.available());     bitmapfactory.decodestream(in, null, options);     // calculate insamplesize     options.insamplesize = calculateinsamplesize(options, reqwidth,             reqheight);     in.reset();     // decode bitmap insamplesize set     options.injustdecodebounds = false;     return bitmapfactory.decodestream(in, null, options); }  public static int calculateinsamplesize(bitmapfactory.options options,         int reqwidth, int reqheight) {     // raw height , width of image     final int height = options.outheight;     final int width = options.outwidth;     int insamplesize = 1;      if (height > reqheight || width > reqwidth) {          final int halfheight = height / 2;         final int halfwidth = width / 2;          // calculate largest insamplesize value power of 2 ,         // keeps both         // height , width larger requested height , width.         while ((halfheight / insamplesize) > reqheight                 && (halfwidth / insamplesize) > reqwidth) {             insamplesize *= 2;         }     }      return insamplesize; }   } 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -