android-Asynchronous Picture Loader

Source: Internet
Author: User

Loading pictures in the ListView is a very common scenario, and the loading of the pictures meets the following requirements:

(1) Whether the picture is in the network or local, the load should not be synchronous, but should be asynchronous to load, such as with Asynctask.

(2) In order to avoid repeated download pictures and page display speed, generally do cache, such as the most common LRUCache.

(3) In order to improve the performance of the ListView, we generally use holder to reuse the ListView item.

The code is probably like this:

public class Mainactivity extends Activity {private imageloader imageloader; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); imageLoader = new Imageloader (New Imagedownloader () {@Overridepublic Bitmap Download (String path, int width, int height) {return Httputil.download (path);}); Final ListView ListView = (ListView) This.findviewbyid (R.id.listview); Button btn = (button) This.findviewbyid (R.ID.BTN); Btn.setonclicklistener (new View.onclicklistener () {@Overridepublic void OnClick (View v) {list<itembean> dataList = Getdatalist (); Listview.setadapter (New Listviewadapter ( Mainactivity.this, DataList));});} @Overrideprotected void OnDestroy () {Super.ondestroy (); Imageloader.destory ();} Private class Listviewadapter extends Baseadapter{private Context context;private list<itembean> datalist;public Listviewadapter (context context, list<itembean> dataList) {this.context = Context;this.datalist = Datalist;} @Overridepublic int GetCount () {return datalist.size ();} @Overridepublic Object getItem (int position) {return datalist.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Holder Holder = null;if (Convertview = = nul L) {holder = new holder (); convertview = new Itemview (context); Holder.itemview = (Itemview) Convertview; Convertview.settag (holder);} Else{holder = (Holder) Convertview.gettag ();} Itemview Itemview = Holder.itemview;imageview Itemimageview = Itemview.getimageview (); ItemBean item = DataList.get ( position);//Set a default picture//If not set, when the page slides to a loaded item, just this item is reused in front of the already displayed item//then this item will first display the picture of the previous item, and so on after its own download completes, Replace this picture,//If the download time is very long, will let users feel the picture is confused! Itemimageview.setimageresource (R.drawable.ic_launcher);//Then download the actual picture imageloader.loadimage (Item.getimagepath (), 50 , Itemimageview); return itemview;} Class Holder{itemview Itemview;}}

Now that the problem arises, consider the following scenario:

Downloading a picture takes a long time, say 10s, and displays 3 item per page.

The first time the user opens the page, the first page should show item0,item1,item2. When the ITEM0 has not finished downloading, the user slides to page 3rd, and the 3rd page should show ITEM6,ITEM7,ITEM8. Then this page of item must be reused for the first page of those item. At this point, the user waits for the page to load. If, ITEM6 reuse is ITEM0,ITEM7 reuse is ITEM1,ITEM8 reuse is item2, when item0 download finished, ITEM6 on the show is item0 on the picture, this is chaotic! Only when item6 own picture download, ITEM6 show is the right picture! If in the process of loading, the user keeps sliding, then the user sees the page is completely chaotic!

The picture loader in this article can avoid this problem, is a colleague wrote, feel very good, directly take over, look at the code:

public class Imageloader {private static final String TAG = "Imageloader";p rivate imagecache cache;private Hashset<stri ng> Cachekeys = new hashset<string> ();p rivate imagedownloader downloader;//Save filepath and ImageView relationships, Because ImageView will reuse, so only this relationship is the right relationship//a ImageView can only correspond to a filepath, a filepath corresponding to a physical file private Weakhashmap<imageview, string> Imageview2filemap = new Weakhashmap<imageview, string> ();//A filepath may correspond to multiple ImageView, Because there may be more than one ImageView display the same picture private hashmap<string, hashset<imageviewreference>> file2imageviewmap = new Hashmap<string, hashset<imageviewreference>> ();//is reading or already in the queue of filepath, read delete private hashset<string > fileinloadset = new hashset<string> ();p ublic imageloader (Imagedownloader downloader) {if (downloader = = null) {throw new RuntimeException ("Imagedownloader can not is null");} This.cache = Imagecache.getinstance (); this.downloader = Downloader;} /** * Set Picture for ImageView * * @param filePath * Picture path * @param width *           Width * @param height * High * @param imageView * @return Cache, directly set, and return True, no asynchronous read, read and reset, return false */public B Oolean LoadImage (string filePath, int width, int height, ImageView ImageView) {string filepathkey = Getkeyforfilepath (file Path, width, height); Bitmap bmp = Cache.get (Filepathkey), if (BMP = = null) {imageviewreference imageviewref = new Imageviewreference (ImageView) ;//Update ImageView and FilePath's latest relationship imageview2filemap.put (ImageView, Filepathkey); hashset<imageviewreference> Imageviewset = File2imageviewmap.get (Filepathkey), if (ImageViewSet = = null) { Imageviewset = new hashset<imageviewreference> (); File2imageviewmap.put (Filepathkey, imageViewSet);} Imageviewset.add (IMAGEVIEWREF);//Do not repeat download if (fileinloadset.contains (Filepathkey)) {return false;} else { Fileinloadset.add (Filepathkey);} Holder Holder = new Holder () Holder.width = Width;holder.height = Height;holder.filepath = Filepath;holder.filepathkey = f Ilepathkey;holder.imageviewref = Imageviewref;new Imageloadtask (). Execute (Holder); return false;} else {imageview.setimagebitmap (BMP); return true;}} Private class Imageloadtask extends AsynctaskSOURCE is here: http://download.csdn.net/download/goldenfish1919/7320823

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.