Android Asynchronous Load Learning Note Four: Optimize network loading images and ListView load optimization with cache

Source: Internet
Author: User

Suppose not to do whatever treatment. Load pictures directly with the network in the case of fast speed, there may be no bad feeling. But suppose you use mobile traffic or a bad network. The problem comes, or the user complains that the traffic is being used too much. Either complain that the picture is loading too slowly. It is not a good experience to start from which angle.

To improve the user experience, we're going to use caching. There are many ways to cache data in Android, and there are more articles about it. http://blog.csdn.net/dahuaishu2010_/article/details/17093139 and http://www.jb51.net/article/38162.htm , for example. Learning today is the LRU cache.

LRU (Least recently used) is the least recently used algorithm, that is, under certain conditions, the LRU cache is the least recently used data removed. To the most recently read data. And the most frequently read, is also the most read times. So. With LRU caching, we can improve application efficiency and user experience. The Andorid itself provides the LRUCache class to implement this caching algorithm.

Using the LRUCache cache in Imageloader:

public class Imageloader {
Private lrucache<string, bitmap> mcaches;//Create LruCache Object
Private ImageView Mimageview;
Private ListView ListView;
Private set<imageasynctask> Mtask;


@SuppressLint ("Newapi")
Public Imageloader (ListView listview) {
This.listview = ListView;
Mtask = new hashset<imageasynctask> ();
int maxmemory = (int) runtime.getruntime (). MaxMemory ();//Get Maximum available memory
int cacheSize = maxmemory/8;//maximum amount of memory to set cache data is 1/8
Mcaches = new lrucache<string, bitmap> (cacheSize) {
@Override
protected int sizeOf (String key, Bitmap value) {
return Value.getbytecount ()///Every time the cache is cached, the size of the bitmap is returned.
}
};
}


@SuppressLint ("Newapi")
/**
* Add cached data. Infer if data exists before adding
* @description:
* @author LDM
* @date 2015-8-11 7:51:04
*/
public void setlrucaches (String url, Bitmap Bitmap) {
if (getlrucaches (URL) = = null) {//assume that the corresponding bitmap of the URL does not exist in the cache. Add the bitmap to the Mcaches
Mcaches.put (URL, bitmap);
}
}


/**
* Get data from the cache
* @description:
* @author LDM
* @date 2015-8-11 7:51:22
*/
@SuppressLint ("Newapi")
Public Bitmap getlrucaches (String URL) {
return Mcaches.get (URL);//Get the corresponding bitmap in the cache via a URL


}


/**
* Get to bitmap from URL
* @description:
* @author LDM
* @date 2015-8-11 1:55:12
*/
Public Bitmap Getbitmapbyurl (String urlstr) {
Bitmap Bitmap = null;
InputStream is = null;
try {
URL url = new URL (urlstr);
HttpURLConnection con = (httpurlconnection) url.openconnection ();
is = new Bufferedinputstream (Con.getinputstream ());
Bitmap = Bitmapfactory.decodestream (IS);
Con.disconnect ();
return bitmap;
}
catch (Exception e) {
E.printstacktrace ();
}
finally {
try {
Is.close ();
}
catch (IOException e) {
E.printstacktrace ();
}
}
return null;
}


public void Loadimgbyasynctask (ImageView img, String URL) {
Mimageview = img;
Remove a picture from the cache
Bitmap Bitmap = getlrucaches (URL);
if (bitmap = = null) {//Assuming there is no picture in, then download from the network
Mimageview.setimageresource (R.drawable.ic_launcher);//Set default picture
New Imageasynctask (URL). Execute (URL);
}
else {//There are pictures in the cache. is displayed directly.
Mimageview.setimagebitmap (bitmap);
}
}


Private class Imageasynctask extends Asynctask<string, Void, bitmap> {
Private ImageView ImageView;
Private String Murl;


Public Imageasynctask (String murl) {
This.murl = Murl;
}


@Override
Protected Bitmap doinbackground (String ... params) {
Bitmap Bitmap = Getbitmapbyurl (Params[0]);//Get Pictures
if (bitmap! = null) {
Setlrucaches (Params[0], bitmap);
}
Return Getbitmapbyurl (Params[0]);
}


@Override
protected void OnPostExecute (Bitmap result) {
ImageView img = (ImageView) listview.findviewwithtag (Murl);
if (img! = NULL && result! = null) {
Imageview.setimagebitmap (result);
}
Mtask.remove (this);
}
}


public void Setimageview (int start, int end) {
for (int i = start; i < end; i++) {
String URL = dataadapter.urls[i];
Bitmap Bitmap = getlrucaches (URL);
if (bitmap = = null) {//Assuming there is no picture in, then download from the network
Imageasynctask task = new Imageasynctask (URL);
Task.execute (URL);
Mtask.add (Task);
}
else {//cache has a picture, it is displayed directly
ImageView img = (ImageView) listview.findviewwithtag (URL);
Img.setimagebitmap (bitmap);
}
}
}
public void Stopalltask () {
if (Mtask.size () >0) {
for (Imageasynctask Task:mtask) {
Task.cancel (FALSE);
}
}
}
}

Data adapter DataAdapter for the corresponding ListView:

public class DataAdapter extends Baseadapter implements Onscrolllistener {
Private Context Mcontext;
Private list<databean> List;
Private Imageloader Mimageloader;
private int msart;
private int mEnd;
public static string[] URLS;
Private ListView ListView;
Private Boolean isfirst;//is the first time to enter
Public DataAdapter (Context mcontext, List<databean> List, ListView listview) {
This.listview = ListView;
This.mcontext = Mcontext;
This.list = list;
Mimageloader = new Imageloader (ListView);
URLS = new String[list.size ()];
for (int i = 0; i < list.size (); i++) {
Urls[i] = List.get (i). Getimgurl ();
}
Isfirst=true;
Listview.setonscrolllistener (this);
}

@Override
public int GetCount () {
TODO auto-generated Method Stub
return List.size ();
}

@Override
Public Object getItem (int arg0) {
TODO auto-generated Method Stub
Return List.get (arg0);
}

@Override
public long getitemid (int arg0) {
TODO auto-generated Method Stub
return arg0;
}

@Override
Public View getView (int arg0, view view, ViewGroup arg2) {
Viewholder holder = null;
if (view = = null) {
Holder = new Viewholder ();
View = Layoutinflater.from (Mcontext). Inflate (r.layout.item_layout, NULL);
HOLDER.IV = (ImageView) View.findviewbyid (R.ID.ITEM_IV);
Holder.titletv = (TextView) View.findviewbyid (r.id.item_title);
Holder.contenttv = (TextView) View.findviewbyid (r.id.item_content);
View.settag (holder);
}
else {
Holder = (viewholder) view.gettag ();
}
Holder.titleTv.setText (List.get (arg0). GetTitle ());
Holder.contentTv.setText (List.get (arg0). GetContent ());
Holder.iv.setTag (List.get (arg0). Getimgurl ());//set tag for ImageView
New Imageloader (). Loaderimagethread (Holder.iv, List.get (arg0). Getimgurl ());//Loading pictures with threads
Mimageloader.loadimgbyasynctask (Holder.iv, List.get (arg0). Getimgurl ());
return view;
}

/***
* The ListView is called during the flow
*/
@Override
public void Onscroll (Abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) {
Msart = firstvisibleitem;//Visible First item
MEnd = Firstvisibleitem + visibleitemcount;//The last item visible
if (isfirst&&visibleitemcount>0) {//data is processed for the first time it is loaded
Mimageloader.setimageview (Msart, mEnd);
Isfirst=false;
}
}

/***
* The ListView is called when the flow state changes
*/
@Override
public void onscrollstatechanged (Abslistview view, int scrollstate) {
if (scrollstate = = Scroll_state_idle) {//Flow stop, load visible item data at this time
Mimageloader.setimageview (Msart, mEnd);
}
else {//Stop loading data
Mimageloader.stopalltask ();
}
}
Class Viewholder {
TextView Titletv;
TextView Contenttv;
ImageView IV;
}
}

Android Asynchronous Load Learning Note Four: Optimize network loading images and ListView load optimization with cache

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.