Android ListView Loads pictures asynchronously and prevents misplaced solutions

Source: Internet
Author: User

Looking for a picture on the web, the root cause of the dislocation of the ListView asynchronous loading image is the reuse of Convertview and the asynchronous operation.

If you do not reuse convertview, there will be no dislocation, but there is no problem with reusing Convertview without an asynchronous operation.

Let me briefly analyze:

When Convertview is reused, the first screen shows 7 records, GetView is called 7 times, and 7 Convertview are created.

When Item1 the screen, Item8 into the screen, there is no new view instance created for ITEM8, ITEM8 multiplexing is

Item1 View If there is no problem with async, although ITEM8 and Item1 point to the same view, but slide to

ITEM8 when the ITEM8 data is brushed, then Item1 data and ITEM8 are the same, because they point to the same piece of memory,

But Item1 has rolled out of the screen you can't see. When the Item1 is visible again, the view Item1 the data.

But when there is an asynchronous download there is a problem, assuming that the Item1 picture download slow, Item8 picture download faster, you roll up

Make Item8 visible, then ITEM8 first show its own downloaded pictures Yes, but wait until the Item1 pictures are downloaded when you find

ITEM8 's pictures also became ITEM1 images, as they were reused for the same view. If the Item1 picture is downloaded more than

ITEM8 picture fast, Item1 first brush on their own downloaded pictures, then you slide down, Item8 pictures have not downloaded, ITEM8

will show Item1 pictures first, because they are the same fast memory, when Item8 their own pictures after downloading Item8 pictures and then brush

Your own, you slide up to make Item1 visible, Item1 pictures will be the same as ITEM8 pictures,

Because they point to the same piece of memory.

The simplest solution is to say it online, set a tag for ImageView, and preset a picture.

When Item1 than Item8 picture download faster, you roll down to make Item8 visible, then ImageView's tag was set to

Item8 URL, when Item1 download finished, because ITEM1 is not visible now the tag is ITEM8 URL, so does not meet the conditions,

Although downloaded but not set to ImageView, tag is always identified as the URL of the picture in the visible view.

The key code is as follows:

Public View GetView (IntPosition, View Convertview, ViewGroup parent) {Viewholder Holder =Null;if (Convertview = =Null) {holder =NewViewholder (); Convertview =Layoutinflater.from (context). Inflate (R.layout.list_item,Null); Holder.img =(ImageView) Convertview.findviewbyid (r.id.userimage); Convertview.settag (holder); }Else{holder =(Viewholder) Convertview.gettag (); } User User =List.get (position);//Set a tag for ImageViewHolder.img.setTag (User.getimgurl ());//Preset a pictureHolder.img.setImageResource (R.drawable.ic_launcher);Final String Tmpimageurl =User.getimgurl ();if (User.getimgurl ()! =Null &&!user.getimgurl (). Equals ("") {Bitmap Bitmap = Imageloader.loadimage (holder.img, User.getimgurl (),  New Imagedownloadcallback () {@Override public void onimagedownloaded (ImageView ImageView, Bitmap Bitmap) {// tag to prevent image dislocation if (Imageview.gettag ()! = null && Imageview.gettag (). Equals (Tmpimageurl)) {Imageview.setimagebitmap ( Bitmap); } } }); if (Bitmap! = nullreturn Convertview;}      

I have a reference to the online data write a ListView asynchronous loading of the picture DEMO:

(1) using the thread pool

There is no thread pool, when the picture is very much, fast sliding the listview because each picture is opened by downloading a thread,

An OOM (out of memory) may occur.

(2) memory, file double cache

SoftReference soft references are also used here

/*** Picture Asynchronous Load Class * *@authorLeslie.fang * @company Enwaysoft **/PublicClassAsyncimageloader {//Maximum number of threadsPrivateStaticFinalint max_thread_num = 10;Private map<string, softreference<bitmap>> imagecaches =Null;PrivateFileutil Fileutil;//Thread poolPrivate Executorservice Threadpools =Null;PublicAsyncimageloader (Context context) {imagecaches =New Hashmap<string, softreference<bitmap>>(); Fileutil =NewFileutil (context); }Public Bitmap LoadImage (Final ImageView ImageView,FinalString ImageUrl,FinalImagedownloadcallback imagedownloadcallback) {Final String filename =ImageUrl. Substring (Imageurl.lastindexof ("/") + 1);Final String filepath = Fileutil.getabsolutepath () + "/" +FileName//First, look for the soft reference.If(Imagecaches.containskey (IMAGEURL)) {Softreference<bitmap> reference =Imagecaches.get (IMAGEURL); Bitmap Bitmap =Reference.get ();//Bitmap objects in soft references may be recycled at any time//If the Bitmap in the soft reference has been reclaimed, the file is searched from theif (Bitmap! =Null{log.i ("AAAA", "cache exists" +filename);ReturnBitmap } }//Find from FileIf(fileutil.isbitmapexists (filename)) {log.i ("aaaa", "File exists" +filename); Bitmap Bitmap =Bitmapfactory.decodefile (filepath);//Rejoin the memory soft reference in Imagecaches.put (IMAGEURL,New softreference<bitmap>(bitmap));ReturnBitmap }//Soft references and files are no longer downloaded from the networkif (imageUrl! =Null &&!imageurl.equals ("")) {if (Threadpools = =Null) {Threadpools =Executors.newfixedthreadpool (Max_thread_num); }Final Handler Handler =NewHandler () {@OverridePublicvoidHandlemessage (Message msg) {if (Msg.what = = 111 && Imagedownloadcallback! =Null) {Bitmap Bitmap =(Bitmap) Msg.obj; Imagedownloadcallback.onimagedownloaded (ImageView, bitmap); } } }; Thread thread =NewThread () {@OverridePublicvoidRun () {log.i ("AAAA"), Thread.CurrentThread (). GetName () + "is running"); InputStream InputStream =Httpservice.getinstance (). GetStream (IMAGEURL); Bitmap Bitmap =Bitmapfactory.decodestream (InputStream);//Image download successfully re-caches and executes callback refresh interfaceif (Bitmap! =Null) {//Added to the soft reference imagecaches.put (IMAGEURL,New softreference<bitmap>(bitmap));//Cache to file systemFileutil.savebitmap (filepath, bitmap); Message msg =NewMessage (); Msg.what = 111; Msg.obj =Bitmap Handler.sendmessage (msg); } } }; Threadpools.execute (thread); }return nullpublic void Shutdownthreadpool () {if (threadpools! = nullnull/** * Picture Download Complete Callback interface * */ Span style= "color: #0000ff;" >public interface Imagedownloadcallback {void onimagedownloaded (ImageView ImageView, Bitmap Bitmap);}}     

The above text is excerpted from http://www.cnblogs.com/lesliefang/p/3619223.html

Demo:http://pan.baidu.com/s/1sjttufj

Related Article

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.