android-Asynchronous Image Loader

Source: Internet
Author: User

Loading images in a ListView is a very common scenario, and several requirements for image loading meet the following:

(1) Whether the screen is on the network or local, the load should not be synchronized. But it should be loaded asynchronously, for example, using Asynctask.

(2) In order to avoid repeated download pictures and page display speed, usually do cache, for example, the most common LRUCache.

(3) In order to improve the performance of the ListView. We usually use holder to reuse the ListView item.

This is probably the code:

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);//First 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 previous item's picture, and so on after its own download, Replace this picture,//fake for example, the following 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 very long time, say 10s. Each page shows 3 item.

The first time the user opens the page, the first page should show item0. Item1,item2. When the ITEM0 is not finished downloading. The user slid to page 3rd. The 3rd page should show the ITEM6,ITEM7,ITEM8. Then this page of item must be reused for the first page of those item.

At this time The user waits for the page to load. If, ITEM6 reuse is the item0. Item7 re-ITEM1,ITEM8 is to reuse item2. When the ITEM0 download is complete. The picture on the ITEM6 is on the ITEM0, which is confusing. Only when Item6 's own pictures have been downloaded, ITEM6 is the right picture to show!

Assuming that the user is constantly sliding during onboarding, the page that the user sees is completely chaotic!

The picture loader in this article can avoid this problem and is written by a colleague. It feels very good. Just take it straight 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. Since ImageView will be reused, it is only the relationship that 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>> ();// Read or already in the queue filepath, read Delete private hashset<string> fileinloadset = new hashset<string> ();p ublic Imageloader (Imagedownloader Downloader) {if (downloader = = null) {throw new RuntimeException ("Imagedownloader can not ' be 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 reads, and then set again after reading. Returns False */public Boolean LoadImage (string filePath, int width, int height, ImageView ImageView) {string filepathkey = GETK Eyforfilepath (FilePath, 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 repeatedly 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 code here: http://download.csdn.net/download/goldenfish1919/7320823

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

android-Asynchronous Image Loader

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.