Android ListView Asynchronous Loading Picture method detailed _android

Source: Internet
Author: User

This example describes the Android ListView asynchronous loading Picture method. Share to everyone for your reference, specific as follows:

First of all, the advantages of this article, open the thread to load the picture asynchronously, and then refresh the UI display picture, and through the weak reference cached network loaded pictures, save the cost of connecting the network again.

This is a great way to do this, but still feel a slight Kashi when loading the picture, especially when the item in ListView is sliding fast.

I looked for a reason, probably in the ListView fast sliding screen when the item is too much and each call GetView method will be asynchronous in the past some time with handler refresh the UI,

This Kashi behavior can occur if the handler refresh UI is more frequent at the same time.

Later thought, in fact, we absolutely do not need to ListView in the background when the slide to load pictures (whether this is the picture is in the cache or on the network), which undoubtedly caused a lot of waste of resources.

All we need to do is to load a picture of the ListView inside a few of the item shown in the ListView slide stop.

Based on the above ideas, I have done some design modification:

1. Start the thread that loads the picture in the adapter GetView method, if ListView is sliding then wait

2. Monitor ListView sliding Stop event, get the top and bottom serial number of the item displayed by ListView, and awaken all thread of loading picture, judge whether the serial number of the loaded picture is in the range, if it is, then continue to load, if not then end thread

Some of the code is as follows:

@Override public View getview (int position, View Convertview, ViewGroup parent) {if (Convertview = null) {CONVERTV
  Iew = minflater.inflate (r.layout.book_item_adapter, NULL);
  Bookmodel model = mmodels.get (position);
  Convertview.settag (position);
  ImageView IV = (ImageView) Convertview.findviewbyid (R.id.sitemicon);
  TextView Sitemtitle = (TextView) Convertview.findviewbyid (r.id.sitemtitle);
  TextView Siteminfo = (TextView) Convertview.findviewbyid (r.id.siteminfo);
  Sitemtitle.settext (Model.book_name);
  Siteminfo.settext (Model.out_book_url);
  Iv.setbackgroundresource (R.DRAWABLE.RC_ITEM_BG);
  Syncimageloader.loadimage (Position,model.out_book_pic,imageloadlistener);
return convertview;  } syncimageloader.onimageloadlistener Imageloadlistener = new Syncimageloader.onimageloadlistener () {@Override public
    void Onimageload (Integer t, drawable drawable) {//bookmodel model = (Bookmodel) getitem (t);
    View view = Mlistview.findviewwithtag (t); if (view!= null) {
      ImageView IV = (ImageView) View.findviewbyid (R.id.sitemicon);
    Iv.setbackgrounddrawable (drawable);
    @Override public void OnError (Integer t) {Bookmodel model = (Bookmodel) getitem (t);
    View view = Mlistview.findviewwithtag (model);
      if (view!= null) {ImageView IV = (ImageView) View.findviewbyid (R.id.sitemicon);
    Iv.setbackgroundresource (R.DRAWABLE.RC_ITEM_BG);
}
  }
};
  public void LoadImage () {int start = Mlistview.getfirstvisibleposition ();
  int end =mlistview.getlastvisibleposition ();
  If (end >= GetCount ()) {end = GetCount ()-1;
  } syncimageloader.setloadlimit (start, end);
Syncimageloader.unlock (); } abslistview.onscrolllistener Onscrolllistener = new Abslistview.onscrolllistener () {@Override public void Onscrolls Tatechanged (abslistview view, int scrollstate) {switch (scrollstate) {case AbsListView.OnScrollListener.SCROLL
        _state_fling:debugutil.debug ("scroll_state_fling"); SyncimageloadEr.lock ();
      Break
        Case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:DebugUtil.debug ("Scroll_state_idle");
        LoadImage ();
        LoadImage ();
      Break
        Case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:syncImageLoader.lock ();
      Break
    Default:break; @Override public void Onscroll (Abslistview view, int firstvisibleitem, int visibleitemcount, int totalitem

 Count) {//TODO auto-generated Method stub}};
Package Cindy.android.test.synclistview;
Import Java.io.DataInputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.lang.ref.SoftReference;
Import Java.net.URL;
Import Java.util.HashMap;
Import android.graphics.drawable.Drawable;
Import android.os.Environment;
Import Android.os.Handler;
  public class Syncimageloader {Private Object lock = new Object ();
  Private Boolean mallowload = true;
  Private Boolean firstload = true;
  private int mstartloadlimit = 0;
  private int mstoploadlimit = 0;
  Final Handler Handler = new Handler (); Private hashmap<string, softreference<drawable>> Imagecache = new hashmap<string, SoftReference<
  Drawable>> ();
    Public interface Onimageloadlistener {public void onimageload (Integer t, drawable drawable);
  public void OnError (Integer t); public void Setloadlimit (int startloadlimit,int stoploadlimit) {if(Startloadlimit > Stoploadlimit)
    {return;
    } mstartloadlimit = Startloadlimit;
  Mstoploadlimit = Stoploadlimit;
    public void Restore () {mallowload = true;
  Firstload = true;
    public void Lock () {mallowload = false;
  Firstload = false;
    public void Unlock () {mallowload = true;
    Synchronized (lock) {lock.notifyall (); } public void LoadImage (Integer t, String ImageUrl, Onimageloadlistener Listener) {final Onimageloadliste
    NER Mlistener = listener;
    Final String mimageurl = IMAGEURL;
    Final Integer mt = t; New Thread (New Runnable () {@Override public void run () {if (!mallowload) {Debugutil.debug
          Prepare to load ");
            Synchronized (lock) {try {lock.wait ();
            catch (Interruptedexception e) {//TODO auto-generated catch block E.printstacktrace (); }} if (MAllOwload && firstload) {loadimage (Mimageurl, MT, Mlistener); } if (mallowload && mt <= mstoploadlimit && Mt >= mstartloadlimit) {LoadImage (Mimag
        Eurl, MT, Mlistener);
  }}). Start (); } private void LoadImage (final String mimageurl,final Integer mt,final onimageloadlistener mlistener) {if (Imagecach
      E.containskey (Mimageurl)) {softreference<drawable> softreference = Imagecache.get (MIMAGEURL);
      Final drawable D = softreference.get (); if (d!= null) {Handler.post (new Runnable () {@Override public void run () {if (MA
            Llowload) {mlistener.onimageload (MT, D);
        }
          }
        });
      Return
      } try {final drawable d = loadimagefromurl (Mimageurl);
      if (d!= null) {Imagecache.put (Mimageurl, New softreference<drawable> (d));
       } handler.post (New Runnable () { @Override public void Run () {if (mallowload) {mlistener.onimageload (MT, D);
    }
        }
      }); The catch (IOException e) {handler.post (new Runnable () {@Override public void run () {MLIs
        Tener.onerror (MT);
      }
      });
    E.printstacktrace ();
    The public static drawable loadimagefromurl (String url) throws IOException {debugutil.debug (URL); if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {file F = new file (environment.getexter
      Nalstoragedirectory () + "/testsynclistview/" +md5.getmd5 (URL));
        if (f.exists ()) {FileInputStream FIS = new FileInputStream (f);
        drawable d = drawable.createfromstream (FIS, "src");
      return D;
      URL m = new URL (URL);
      InputStream i = (inputstream) m.getcontent ();
      DataInputStream in = new DataInputStream (i);
      FileOutputStream out = new FileOutputStream (f); byte[] buffer = new BYTE[1024];
      int byteread=0;
      while ((Byteread = in.read (buffer))!=-1) {out.write (buffer, 0, byteread);
      } in.close ();
      Out.close ();
      drawable d = drawable.createfromstream (i, "src");
    return Loadimagefromurl (URL);
      }else{url m = new URL (URL);
      InputStream i = (inputstream) m.getcontent ();
      drawable d = drawable.createfromstream (i, "src");
    return D;

 }
  }
}

In addition to its own weak reference cache picture, I also added a local SD card cache image (both of these caching methods are beneficial, if the picture often changes the recommended memory cache picture, if it is not often modified picture recommended SD card cache)

For more information on Android-related content readers can view the site topics: "Android Development Introduction and Advanced Course", "Android Multimedia operating skills Summary (audio, video, recording, etc.)", "Android Basic Components Usage Summary", " Android View tips Summary, Android layout layout tips and a summary of Android controls usage

I hope this article will help you with the Android program.

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.