Get Picture text resource display from network based on Android4.0listview

Source: Internet
Author: User

In some of the usual Android learning videos, they are all based on Android to use the ListView, and I see that it is going to access the network fetch data in the UI thread, but it won't work after Android4.0.

First, let's take a look at our thoughts:

We need to download a copy of the XML data from the Web that contains the text and image paths that need to be displayed. So the first thing we need is to download the data, download the data after the completion of the picture in the adapter to download the picture, and then display it. This is the basic idea. But doing it will find some problems, such as how we can guarantee that the data is downloaded completely before we bind the adapter and the data to them. Then if we are in a sub-thread to complete the download data, after the download is done to bind the adapter, this seems to be possible, but there are some problems, we need to customize the adapter and then to update ImageView, which requires the use of handler. Then download to complete the binding adapter, how to update the UI in the adapter, the adapter is running on the sub-thread, if the UI thread handler as a parameter to adapter, then adapter inside send a message to the UI handler, Can the UI of the handler how to find to belong to the ListView of an item ImageView, so this does not work.

So the correct approach should be: we should bind the adapter in the UI thread, we first use a list without values to pass to adapter, when the adapter is running in the UI thread, while the UI thread to start a thread to download data, if the download is complete, send using handler send a message , this time handler should use the adapter in the handler, because adapter is running on the UI thread, no need to have looper, directly use handler handlermessage () just fine. Then in the adapter GetView method, in the open a thread to complete the download of the picture, if the download is complete, then use adapter handler send a message, define a tag display download completed. If the download fails to send an empty message, what is-1 so that you can adapter in the handler to deal with ImageView, and then update it. This is the approximate idea, below please see source analysis:

Mainactivity.java His main function is to bind the data and adapters, the ListView and the adapter, to start a thread to go now. xml file

public class Mainactivity extends Activity{private ListView listview;// listview@overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate) showing the data; Setcontentview (R.layout.activity_main); File cache = new file (Environment.getexternalstoragedirectory (), "Cahce");//Create a cached directory folder if (!cache.exists ()) Cache.mkdirs (); listview = (ListView) Findviewbyid (R.id.listview);//Find listviewlist<contacts> data = new Arraylist<contacts> ();//First Use empty datalistviewadapter adapter = new Listviewadapter (This,r.layout.item_listview, Data,cache);//bind adapter, this time make adapter run in UI thread Listview.setadapter (adapter);//Bind ListView and Adapter New MyThread (). Start ();// Start the thread to download the. XML Data}}class MyThread extends thread{@Overridepublic void Run () {try{contacesservice.getcontacts ( Listviewadapter.mhandler);//download. XML data} catch (Exception e) {ListViewAdapter.mHandler.sendEmptyMessage (-1);//An exception is used, You must only use adapter's handler to send a message informing you that the download failed E.printstacktrace ();}} 
Listadapter.java, his function is mainly to display the data on the ListView, and then it needs to start the thread to download the picture, there is a message about this listview that needs to be sent through the handler and then reached here to deal with.

public class Listviewadapter extends baseadapter{private static final int OK = 2;//picture Download complete msg.what=1private static final in T faile = -1;//picture download failed msg.what=-1private static ImageView image;private File cache; @SuppressLint ("Handlerleak") public static Handler Mhandler = new Handler ()//handler{@SuppressWarnings of the data UI ("unchecked") public void Handlemessage ( Android.os.Message msg) {if (msg.what = = 1) {Data.addall ((list<contacts>) msg.obj);//Data Download complete update data}if (image!= Null && msg.what = = OK) {Image.setimageuri (Uri) msg.obj);//image Download complete update ImageView}}; private static list<contacts> data;//data private int itemlistviewl;//layout idprivate layoutinflater inflater;// Layout shim Public Listviewadapter (Activity mainactivity, int itemlistview, list<contacts> data,file cache) { Listviewadapter.data = DATA;THIS.ITEMLISTVIEWL = Itemlistview;this.cache = Cache;inflater = (LayoutInflater) Mainactivity.getsystemservice (Context.layout_inflater_service);} Total number of Get item @overridepublic int GetCount () {REturn data.size ();} Get the data for an item @overridepublic Object getItem (int position) {return data.get (position);} Gets the position of the data in which the item is located @overridepublic long getitemid (int position) {return position;} Every entry that needs to be displayed in the ListView will call the method to get a view and then display the corresponding data @overridepublic view GetView (int position, view Convertview, ViewGroup parent) {Viewholder holder = null;if (Convertview = = null) {Convertview = inflater.inflate (ITEMLISTVIEWL, NULL); Holder = new Viewholder (); Holder.imageview = (ImageView) Convertview.findviewbyid (r.id.imageview); Holder.textview = ( TextView) Convertview.findviewbyid (R.id.textview); Convertview.settag (holder);} Else{holder = (Viewholder) Convertview.gettag ();} Contacts contact = data.get (position); Holder.textview.setText (contact.name); Asynctask (Contact.path, Holder.imageview,cache); return convertview;} /** * Download Picture * @param path Download path * @param imageView download image needs to display ImageView * @param cache download picture need to save folder */private void Asynctask (f Inal String Path, final ImageView imageview,final File cache) {Runnable RunnabLe = new Runnable () {public void run () {Try{uri Uri = contacesservice.getimage (Path,cache); System.out.println ("uri=" +uri); if (uri! = null) {Message msg = Message.obtain (); msg.what = Ok;msg.obj = Uri;image = Imagevi Ew;mhandler.sendmessage (msg);//download successfully sent Message}else{mhandler.sendemptymessage (faile);//download failed to send message}} catch (Exception e) { Mhandler.sendemptymessage (Faile);//download failed to send message e.printstacktrace ();}}; New Thread (runnable). Start ();//start thread start Download}/** * When more entries are used to increase performance * @author Administrator * */class Viewholder{imageview ImageView; TextView TextView;}}

Contacesservice.java, his role is to encapsulate the data downloaded from the network, download a variety of data, send a variety of messages

/** * Various data Download implementation class * * @author Administrator * */public class contacesservice{/** * download. xml file Driver class * * @param handler * Handler in adapter that needs to send a message * @throws Exception */public static void Getcontacts (Handler Handler) throws Exception{stri ng path = "Http://192.168.1.101:8080/web/list.xml"; HttpURLConnection conn = (httpurlconnection) new URL (path). OpenConnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"), if (Conn.getresponsecode ()) {System.out.println ("11111"); InputStream InputStream = Conn.getinputstream ();p arserxml (InputStream, handler);}} /** * Download and parse the. xml file to generate a collection using handler sent to adapter processing * * @param inputstream * Input stream * @param handler need to send the message adapter in the HA Ndler * @throws Exception * @throws ioexception */private static void Parserxml (InputStream inputstream, Handler Handler) Throws Exception, Ioexception{xmlpullparser parser = Xml.newpullparser ();p arser.setinput (InputStream, "UTF-8"); list<contacts> Contacts = new arraylist<contacts> (); System.Out.println (2222); Contacts Contact = null;int event = Parser.geteventtype (), while (xmlpullparser.end_document! = event) {switch (event) { Case XmlPullParser.START_TAG:if (' Contact '. Equals (Parser.getname ())) {contact = new Contacts (); contact.id = Integer.valueof (parser.getattributevalue (0));} if ("Name". Equals (Parser.getname ())) {contact.name = Parser.nexttext ();} if ("image". Equals (Parser.getname ())) {Contact.path = Parser.getattributevalue (0);} Break;case XmlPullParser.END_TAG:if ("Contact", Equals (Parser.getname ())) {Contacts.add (contact), contact = null;} break;} event = Parser.next ();} if (contacts.size () = 0) {Message msg = Message.obtain (); msg.what = 1;msg.obj = Contacts; System.out.println (contacts);//used to test whether the download succeeded Handler.sendmessage (msg);//send adapter, let him update the value of data} else{ Handler.sendemptymessage (-1);//Failed to send -1}}/** * To download pictures from the network and save local, when the local presence of the picture will be directly read * * @param path * Picture of paths * @param c Ache * Cache Two directories * @return * @throws Exception */public static Uri getImage (String path, File cache)Throws Exception{file LocalFile = new File (cache, MD5.GETMD5 (path) + path.substring (Path.lastindexof (".")); /md//5 Encryption if (Localfile.exists ()) {return uri.fromfile (localfile);} else{httpurlconnection conn = (httpurlconnection) The new URL (path). OpenConnection (); Conn.setconnecttimeout (); Conn.setrequestmethod ("GET"); if (200 = = Conn.getresponsecode ()) {System.out.println ("11111"); InputStream InputStream = Conn.getinputstream (); FileOutputStream fos = new FileOutputStream (localfile); int len;byte[] buffer = new Byte[1024];while (len = inputstream.re AD (buffer))! =-1) {fos.write (buffer, 0, Len);} Fos.close (); Inputstream.close (); return Uri.fromfile (LocalFile);}} return null;}}
Domai class

public class Contacts{public int id;public string Name;public string Path;public Contacts () {}public Contacts (int id, St ring name, String path) {super (); this.id = Id;this.name = Name;this.path = path;} @Overridepublic String toString () {return "Contacts [id=" + ID + ", name=" + name + ", path=" + path + "]";}}

Then the MD5 cryptography named Class:

public class MD5 {public static string getMD5 (string content) {try {messagedigest digest = messagedigest.getinstance ("MD5" );d Igest.update (Content.getbytes ()); return gethashstring (Digest);} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} return null;}    private static String gethashstring (MessageDigest Digest) {        StringBuilder builder = new StringBuilder ();        For (Byte b:digest.digest ()) {            builder.append (integer.tohexstring ((b >> 4) & 0xf));            Builder.append (integer.tohexstring (b & 0xf));        }        return builder.tostring ();    }}
About layouts: Main.xml

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent " android:orientation= "vertical" >    <listview        android:layout_width= "match_parent"        android:layout _height= "Match_parent"        android:id= "@+id/listview"/></linearlayout>
Item.xml
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "Horizontal" >    <imageview        android:id= "@+id/imageview"        android:layout_width= "50DP"        android:layout_height= "50DP"/>    <textview        android:layout_width= "Wrap_content"        android: layout_height= "Wrap_content"        android:id= "@+id/textview"        android:textsize= "20SP"/></ Linearlayout>

Finally, due to the need to access the network and write read data from the SD card, permissions are required:

<uses-permission android:name= "Android.permission.INTERNET"/>    <uses-permission android:name= " Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "/>    <uses-permission android:name=" Android.permission.WRITE_EXTERNAL_STORAGE "/>

This will be done.

The final results are as follows:







Get Picture text resource display from network based on Android4.0listview

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.