Reprint please indicate the source, welcome reprint. http://write.blog.csdn.net/postedit/51533261
This blog summarizes the MU lesson network on the asynchronous loading of the knowledge points of the picture, and everyone to share, there is a feeling to hear incoherent can be seen since.
After reading this blog post, you will learn the following knowledge:
1. How to convert a URL (or a inputstream) to a JSON string information.
2. How to use the plugin to write a model Class I think is perfect to prepare for parsing JSON.
Basic usage of 3.AsyncTask.
Basic usage of 4.GOSN.
5.Adapter of commonly used optimization notation.
6. Cache the already loaded pictures via LRUCache.
7.listview loads complex item layouts efficiently.
8. Write the As Widget for the JSON entity class.
Well, directly on the code, the code contains a detailed explanation.
Package Com.robin.loadimageinlistview;import Android.os.asynctask;import Android.os.bundle;import Android.support.v7.app.appcompatactivity;import Android.widget.listview;import Com.google.gson.Gson;import Java.io.bufferedreader;import Java.io.ioexception;import Java.io.inputstream;import Java.io.InputStreamReader; Import Java.net.url;import Java.util.list;public class Mainactivity extends Appcompatactivity {private ListView LISTVI ew @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); ListView = (ListView) Findviewbyid (R.id.lv_main); String URL1 = "http://www.imooc.com/api/teacher?type=4&num=30"; New Myasynctask (). Execute (URL1); } class Myasynctask extends Asynctask<string, Void, list<newsbean.beandata>> {//<strong><span sty le= "COLOR: #ff0000;" > (Knowledge point 3) </span></strong> @Override protected list<newsBean.beandata> doinbackground (String ... params) {return getjsondata (params[0]); } @Override protected void OnPostExecute (list<newsbean.beandata> beandatas) {Super.onposte Xecute (Beandatas); Newsadapter adapter = new Newsadapter (Mainactivity.this, Beandatas, ListView); Listview.setadapter (adapter); }}/** * Get JSON string via URL <strong><span style= "color: #ff0000;" > (Knowledge point 2) </span></strong> * * @param URL * @return list<newsbean.beandata> */privat E list<newsbean.beandata> getjsondata (string url) {string jsonstring = null; try {jsonstring = readstream (new URL). OpenStream ()); } catch (IOException e) {e.printstacktrace (); } Gson Gson = new Gson (); if (jsonstring==null| | "". Equals (jsonstring)) return null;//If the jsonstring returns a problem, it is not resolved. Newsbean Newsbean = Gson.fromjson (jsonstring, NewsBean.class);//<span style= "color: #ff0000;" ><strong> (Knowledge point 4) </strong></span> the GOSN package needs to be imported into project. How to guide, not detailed said, go to Google return Newsbean.getdata (); }/** * How to convert a URL (or a inputstream) to a JSON string information. <strong><span style= "color: #ff0000;" > (Knowledge point 1) </span></strong> * * @param is * @return String */private string Readstream (Inpu TStream is) {String result = ""; InputStreamReader ISR; String Line; try {ISR = new InputStreamReader (IS, "utf-8");//byte flow into a character stream bufferedreader br = new BufferedReader (IS R); while (line = Br.readline ()) = null) {result + = line; }} catch (IOException e) {e.printstacktrace (); } return result; }}
Let's start adapter.(Knowledge point 5)
Package Com.robin.loadimageinlistview;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.abslistview;import Android.widget.baseadapter;import Android.widget.imageview;import Android.widget.listview;import Android.widget.textview;import Java.util.list;public class Newsadapter extends Baseadapter implements abslistview.onscrolllistener{private list<newsbean.beandata> Newsbeans; Private Layoutinflater Minflater; Private Imageloader Imageloader; private int mstart,mend; public static string[] urls;//the URL of the picture you want to load private Boolean IsFirst = false;//controls The first time you enter the listview, load the data public newsadapt ER (context context, List<newsbean.beandata> Newsbeans, ListView listview) {//Initialize data This.newsbeans = Newsbeans ; This.minflater = Layoutinflater.from (context); Imageloader = new Imageloader (listView);//Make sure there is only one lrucache URLS = new String[newsbeans.size ()]; for (int i=0;i<newsbeans.size (); i++) {//Gets the URL of the picture in Newsbeans urls[i] = Newsbeans.get (i). Getpicsmall (); } IsFirst = true; Listview.setonscrolllistener (this); } @Override public int getcount () {return newsbeans.size (); } @Override public Object getItem (int position) {return newsbeans.get (position); } @Override public long getitemid (int position) {return position; } @Override public View getView (int position, view Convertview, ViewGroup parent) {Viewholder viewholder;// Optimization with Viewholder is also a template for writing GetView methods similar to the ListView adapter. if (convertview==null) {viewholder = new Viewholder (); Convertview = Minflater.inflate (r.layout.item_layout,null); Viewholder.ivicon = (ImageView) Convertview.findviewbyid (R.id.iv_icon); Viewholder.tvtitle = (TextView) Convertview.findviewbyid (r.id.tv_title); Viewholder.tvcontent = (TextView) Convertview.findviewbyid (r.id.tv_content); Convertview.settag (Viewholder); }else{//If the Convertview is not empty, you do not have to load the layout again, because loading the layout takes a long time, resulting in a listview Viewholder = (Viewholder) convertview.gettag (); } viewHolder.ivIcon.setImageResource (R.mipmap.ic_launcher); String url = newsbeans.get (position). Getpicsmall (); ViewHolder.ivIcon.setTag (URL);//URL as tag imageloader.showimagebyasynctask (Viewholder.ivicon,url); ViewHolder.tvTitle.setText (Newsbeans.get (position). GetName ()); ViewHolder.tvContent.setText (Newsbeans.get (position). GetDescription ()); return convertview; } @Override public void onscrollstatechanged (Abslistview view, int scrollstate) {///sliding state changed when <span style= "color: #f f0000; " ><strong> (Knowledge point 7) </strong></span> if (scrollstate==scroll_state_idle) {//stop scrolling, load visible ima Geloader.loadimage (Mstart,mend); }else{//Stop loading imageloader.cancelalltask (); }} @Override public void onscroll (Abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) { The entire slide will be called Mstart = firstvisibleitem;//First visible element mEnd =firstvisibleitem+visibleitemcount;//last visible element = First visible element + Number of visible elements if (isFirst && visibleitemcount > 0) {//The first time the load is called, the picture is displayed Imageloader.loadimage (mstart,m END); Isfirst=false; }} class viewholder{public TextView tvtitle; Public TextView tvcontent; Public ImageView Ivicon; }} RightKnowledge Point 7A little explanation, when the item layout is very complex, this is the user area frequent scrolling listview,listview will frequently call the GetView method to get the item, causing the lag, however, during the usual use process, we find that the general user is not too careful when scrolling the content, When we stop scrolling, we go back to the content, so we consider this problem to be solved if the right to display the content is moved from GetView to the scrolling event processing.
The next most important control of the picture cache and the loaded classes
Package Com.robin.loadimageinlistview;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.asynctask;import Android.util.lrucache;import Android.widget.imageview;import Android.widget.ListView; Import Java.io.bufferedinputstream;import Java.io.ioexception;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Java.util.hashset;import Java.util.Set;public class Imageloader {Private lrucache<string,bitmap> cache;//for caching pictures private ListView listview; Private set<newsasynctask> mtask;//admin asynctask Public Imageloader (ListView listview) {//Initialize some data This.listv Iew = ListView; This.mtask = new hashset<> (); int maxmemry = (int) runtime.getruntime (). MaxMemory ();//Gets the maximum memory available for the current app int cacheSize = maxmemry/4;//with maximum One-fourth as the available cache size Small This.cache = new Lrucache<string,bitmap> (cacheSize) {//Initialize LruCache @Override protected int sizeOf (String key, Bitmap VAlue) {return value.getbytecount ();//the size of each cache, that is, the size of the bitmap}}; /** * Save content to LRUCache * @param URL * @param bitmap */public void Addbitmaptocache (String url,bitma P bitmap) {if (Getbitmapfromcache (URL) ==null) {//Save if not saved. Cache.put (URL,BITMAP); }}/** * Get Bitmap * from LRUCache * @param URL * @return Bitmap */Public Bitmap Getbitmapfromcache (St Ring URL) {return this.cache.get (URL); /** * Convert image URL to Bitmap * @param urlstring * @return Bitmap */Public Bitmap Getbitmapfromurl (String urlstring) {Bitmap Bitmap; InputStream Is=null; try {URL url = new URL (urlstring); HttpURLConnection connection = (httpurlconnection) url.openconnection (); is = new Bufferedinputstream (Connection.getinputstream ()); Bitmap = Bitmapfactory.decodestream (IS); Connection.disconnect (); return bitmap; } catch (IOException e) {e.printstacktrace (); }finally {try {if (is!=null) {is.close (); }} catch (IOException e) {e.printstacktrace (); }} return null; } public void Showimagebyasynctask (ImageView imageview,string URL) {//improved, control of get picture changed from original GetView to scroll state. Bitmap Bitmap = getbitmapfromcache (URL);//Get Picture from cache if (bitmap==null) {//If not, set default picture Imageview.setimageres Ource (R.mipmap.ic_launcher); }else{//set the current picture Imageview.setimagebitmap (bitmap) if there is one; }} Private class Newsasynctask extends asynctask<string,void,bitmap>{private String URL; Public newsasynctask (String url) {this.url = URL; } @Override protected Bitmap doinbackground (String ... params) {string url = params[0]; Bitmap Bitmap = GetBitmapfromurl (URL);//Get the network picture if (bitmap!=null) {Addbitmaptocache (URL,BITMAP);//will not be cached in the cache to load the picture } return bitmap; } @Override protected void OnPostExecute (Bitmap Bitmap) {super.onpostexecute (BITMAP); ImageView ImageView = (ImageView) listview.findviewwithtag (URL); if (imageview!=null&&bitmap!=null) {//Determine if the corresponding imageView of this URL corresponds, the corresponding words only set the picture, Imageview.setimagebitmap (b ITMAP); }}}/** * Load all pictures from start to end * @param start * @param end */public void Loadi Mage (int start,int end) {for (int i= start;i<end;i++) {//Gets the URL for the image in the array String url = newsadapter.urls[ I]; Bitmap Bitmap = getbitmapfromcache (URL); if (bitmap==null) {//is not going to download newsasynctask newsasynctask = new Newsasynctask (URL); Newsasynctask.execute (URL); Mtask.add (Newsasynctask); }else{ImageView ImageView = (ImageView) listview.findviewwithtag (URL);//Findviewwithtag Find ImageView , this tag is ImageView URL imageview.setimagebitmap (bitmap); }}} public void Cancelalltask () {if (mtask!=null) {for (Newsasynctask task:mtask) { Task.cancel (FALSE); } } }}
Finally send a small plug-in(Knowledge point 8), only hate myself directed too late, if there is a magic, entity class is not so difficult to write. Again to share to everyone, especially when the enterprise development, often can use, on the GIT address, including usage, installation is very detailed.
Https://github.com/zzz40500/GsonFormat
All right, that's about it, upload a picture.
Finally thank you, like please praise, have doubts, can reply to exchange, there are errors, please point out. Thx.
Reprint please indicate the source, welcome reprint. http://write.blog.csdn.net/postedit/51533261
Aston
Android Asynchronous loading