Android-building a simple server +listview asynchronously loading data
May 6, 2014
This blog post is to teach you how to build a server in the MyEclipse, and communicate with the mobile phone, asynchronously loading data.
The author uses myeclipse, you can also create a Java Web project directly with Eclipse, the ADT bundle provided by Google is unable to create a Web project, and the reader can download the eclipse for javeee developer IDE.
Here's how to create a Web project in MyEclipse and deploy it to Tomcat, and I won't say much about the configuration of Tomcat here.
Create a Web project named Test, as shown in the project structure:
I created a images folder and List.xml file, Images folder is a few pictures, is what we want to get, List.xml is an XML file, the content is as follows:
<?xml version= "1.0" encoding= "UTF-8"? ><contacts><contact id= "1" ><name> Frog 1</name> <image src= "http://192.192.8.233:8080/Test/images/1.gif"/></contact><contact id= "2" ><name > Frog 2</name><image src= "Http://192.192.8.233:8080/Test/images/2.gif"/></contact><contact Id= "3" ><name> frog 3</name><image src= "Http://192.192.8.233:8080/Test/images/3.gif"/></ Contact><contact id= "4" ><name> frog 4</name><image src= "http://192.192.8.233:8080/Test/ Images/4.gif "/></contact><contact id=" 5 "><name> frog 5</name><image src="/http 192.192.8.233:8080/test/images/5.gif "/></contact><contact id=" 6 "><name> Frog 6</name> <image src= "http://192.192.8.233:8080/Test/images/6.gif"/></contact><contact id= "7" ><name > Frog 7</name><image src= "Http://192.192.8.233:8080/Test/images/7.gif"/></contact><contact Id= "8" ><name> frog 8</name><image src= "Http://192.192.8.233:8080/Test/images/8.gif"/></contact>< Contact id= "9" ><name> frog 9</name><image src= "Http://192.192.8.233:8080/Test/images/9.gif"/> </contact><contact id= "Ten" ><name> Frog 10</name><image src= "http://192.192.8.233:8080/ Test/images/10.gif "/></contact><contact id=" one "><name> Frog 11</name><image src=" http ://192.192.8.233:8080/test/images/11.gif "/></contact><contact id=" ><name> Frog 12</name ><image src= "http://192.192.8.233:8080/Test/images/12.gif"/></contact><contact id= "><" name> frog 13</name><image src= "Http://192.192.8.233:8080/Test/images/13.gif"/></contact>< Contact id= "+" ><name> Frog 14</name><image src= "Http://192.192.8.233:8080/Test/images/14.gif"/ ></contact><contact id= "><name> frog 15</name><image src=" http://192.192.8.233:8080/test/images/15.gif "/></contact><contact id=" ><name> frog 16</name><image src= " Http://192.192.8.233:8080/Test/images/16.gif "/></contact><contact id=" ><name> Frog 17</ Name><image src= "http://192.192.8.233:8080/Test/images/17.gif"/></contact><contact id= ">" <name> frog 18</name><image src= "Http://192.192.8.233:8080/Test/images/18.gif"/></contact> </contacts>
We can see that the outermost layer of the list.xml is a contacts tag with multiple sub-contact labels, each containing the ID, name, and image content, which is what we want to parse below for each contact object.
Here to mention, we see the image tag, src is the image URL address, this address is the IP address of my PC, the reader in the test need to change this IP address to your PC's IP address, how to get? run->cmd->ipconfig/all to view the IPv4 address, which is the IP address of your computer.
After creating the Web project, we test it on the computer and enter the address in the browser:
Http://192.192.8.233:8080/Test/list.xml
See above, we can already access to our service, below we can develop our client:
I have created a 07_dataasyncload project here:
The directory structure is as follows:
To set permissions in Androidmanifest.xml because of the need for networking:
<!--networking rights-- <uses-permission android:name= "Android.permission.INTERNET"/>
Based on the service-side list.xml, we need to define an entity class:
/07_dataasyncload/src/com/wwj/domain/contact.java
Package com.wwj.domain;/** * Contacts entity class * * @author WWJ * */public class Contact {public int id;public String name;pub Lic String image;public Contact (int id, string name, string image) {this.id = Id;this.name = Name;this.image = image;} Public contact () {}}
To access the server and parse the XML file, we define a service class:
/07_dataasyncload/src/com/wwj/service/contactservice.java
Package Com.wwj.service;import Java.io.file;import Java.io.fileoutputstream;import java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;import Java.util.arraylist;import Java.util.List;import Org.xmlpull.v1.xmlpullparser;import Com.wwj.domain.contact;import Com.wwj.utils.md5;import Android.net.Uri;import Android.util.xml;public class ContactService {/** * get contacts * @return */public static list<contact> getcontacts () thro WS exception{//Server file path string path = "Http://192.192.8.233:8080/Test/list.xml"; HttpURLConnection conn = (httpurlconnection) new URL (path). OpenConnection (); conn.setconnecttimeout (5000);// Set timeout of 5 Seconds Conn.setrequestmethod ("GET");//Set Request mode if (conn.getresponsecode () = = 200) {//Connection successful return code 200return Parsexml ( Conn.getinputstream ());} return null;} /** * Parsing XML files using the Pull parser * @param XML * @return * @throws Exception */private static list<contact> Parsexml (inputst Ream XML) throws exception{list<contact> contacts = new arraylist<contact> (); Contact CONTact = NULL; Xmlpullparser Pullparser = Xml.newpullparser ();p ullparser.setinput (Xml, "UTF-8"); int event = Pullparser.geteventtype ( );//Get Start document syntax while (event! = xmlpullparser.end_document) {//As long as the document end event is not equal, loop resolves switch (event) {case Xmlpullparser.start_ tag://start label if ("Contact". Equals (Pullparser.getname ())) {contact = new contact (); contact.id = new Integer ( Pullparser.getattributevalue (0));} else if ("name". Equals (Pullparser.getname ())) {contact.name = Pullparser.nexttext ();//Gets the text value of the back node}else if ("image"). Equals (Pullparser.getname ())) {contact.image = Pullparser.getattributevalue (0);//Gets the value of the first property}break;case xmlpullparser.end_tag://end Tag if ("Contact". Equals (Pullparser.getname ())) {Contacts.add (contact);// Add the Contact object to the collection contact = null;} break;} event = Pullparser.next ();//Go to next label}return contacts;} /** * Get the network picture, if the picture exists in the cache, return the picture, otherwise load the picture from the network and cache it * @param path picture paths * @return */public static Uri getImage (String path, Fil E cachedir) throws exception{//path, MD5->32 string. Jpgfile LocalFile = new File (Cachedir, MD5.GEtMD5 (path) + path.substring (Path.lastindexof (".")); if (localfile.exists ()) {return uri.fromfile (localfile);} Else{httpurlconnection conn = (httpurlconnection) new URL (path). OpenConnection (); conn.setconnecttimeout (5000); Conn.setrequestmethod ("GET"), if (conn.getresponsecode () = =) {FileOutputStream OutStream = new FileOutputStream ( LocalFile); InputStream InputStream = Conn.getinputstream (); byte[] buffer = new Byte[1024];int len = 0;while (len = InputS Tream.read (buffer))! =-1) {outstream.write (buffer, 0, Len);} Inputstream.close (); Outstream.close (); return Uri.fromfile (LocalFile);}} return null;}}
The above code has clearly defined the way to get the server-side data, the approximate process is: pass a network path, through the URL to open the connection, through the HttpURLConnection connection server, get input stream, parse the XML file to obtain data.
The above code obtains the network picture, needs to carry on the MD5 encryption computation, the concrete method is as follows:
/07_dataasyncload/src/com/wwj/utils/md5.java
Package Com.wwj.utils;import Java.security.messagedigest;import Java.security.nosuchalgorithmexception;public Class MD5 {/** * MD5 encryption Algorithm * * @param content * @return */public static string getMD5 (string content) {try {messagediges T digest = messagedigest.getinstance ("MD5");d igest.update (Content.getbytes ()); return gethashstring (Digest);} catch (NoSuchAlgorithmException e) {e.printstacktrace ();} return null;} /** * Get Hash String * * @param digest * @return */private static string gethashstring (MessageDigest digest) {StringBuilder b Uilder = new StringBuilder (); for (Byte B:digest.digest ()) {Builder.append (integer.tohexstring ((b >> 4) & 0xf)) ; Builder.append (integer.tohexstring (b & 0xf));} return builder.tostring ();}}
OK, so our service class is finished, and then we load the data asynchronously in Mainactivity:
/07_dataasyncload/src/com/wwj/asyntask/mainactivity.java
Package Com.wwj.asyntask;import Java.io.file;import Java.util.list;import com.wwj.adapter.contactadapter;import Com.wwj.asyntask.r;import Com.wwj.domain.contact;import Com.wwj.service.contactservice;import Android.app.activity;import Android.os.bundle;import Android.os.environment;import Android.os.Handler;import Android.os.message;import Android.widget.listview;public class Mainactivity extends Activity {listview listview; File Cache; Cache file Handler handler = new Handler () {public void Handlemessage (Message msg) {listview.setadapter (new Contactadapter (Ma Inactivity.this, (list<contact>) msg.obj, R.layout.listview_item, cache);}}; @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main), ListView = (ListView) This.findviewbyid (R.id.listview), cache = new File ( Environment.getexternalstoragedirectory (), "cache"); Instantiate the cache file if (!cache.exists ()) cache.mkdirs (); If the file does not exist, create//open a thread to load the data new thread (new Runnable () {PUBlic void Run () {try {list<contact> data = contactservice.getcontacts ();//handler to send Message Handler.sendmessage ( Handler.obtainmessage (data));} catch (Exception e) {e.printstacktrace ();}}}). Start ();} @Overrideprotected void OnDestroy () {//delete cache for (File file:cache.listFiles ()) {File.delete ();} Cache.delete (); Super.ondestroy ();}}
Here we open a thread to load the data because the network operation cannot be done in the UI thread, and the message is sent through hanlder after the data is loaded, displaying the list.
In general, we need to obtain the image processing, we have a number of methods, the most commonly used is handler+thread and asynctask two kinds, concrete implementation to see:
/07_dataasyncload/src/com/wwj/adapter/contactadapter.java
We define a list adapter to populate our data, and the asynchronous loading of our images is also implemented here:
Package Com.wwj.adapter;import Java.io.file;import Java.util.list;import android.content.context;import Android.net.uri;import Android.os.asynctask;import Android.view.layoutinflater;import Android.view.View;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.imageview;import Android.widget.textview;import Com.wwj.asyntask.r;import Com.wwj.domain.contact;import com.wwj.service.contactservice;/** * Custom Adapter * * @author WWJ * */public class Contactadapter extends Baseadapter {private List<contact> data; Cache data private int listviewitem; Entry Idprivate File cache; Cache files Layoutinflater Layoutinflater;public contactadapter (context context, list<contact> Data,int ListviewItem , File cache) {This.data = Data;this.listviewitem = Listviewitem;this.cache = Cache;layoutinflater = (layoutinflater) cont Ext.getsystemservice (Context.layout_inflater_service);//Get Layout Fill Service}/** * Total number of data */public int GetCount () {return Data.size ();} /** * The data corresponding to the set is obtained according to the data index */publIC Object getItem (int position) {return data.get (position);} public long getitemid (int position) {return position;} /** * This method is called when a ListView is displayed for each entry */public view GetView (int position, view Convertview, ViewGroup parent) {ImageView imag Eview = null; TextView TextView = null;if (Convertview = = null) {Convertview = layoutinflater.inflate (ListViewItem, NULL);//Get the item's view pair Like ImageView = (ImageView) Convertview.findviewbyid (r.id.imageview); TextView = (TextView) Convertview.findviewbyid ( R.id.textview); Convertview.settag (New Datawrapper (ImageView, TextView));} else {Datawrapper Datawrapper = (datawrapper) convertview.gettag (); ImageView = Datawrapper.imageview;textview = Datawrapper.textview;} Contact Contact = Data.get (position); Textview.settext (contact.name); Asyncimageload (ImageView, contact.image); return Convertview;} private void Asyncimageload (ImageView ImageView, String path) {asyncimagetask asyncimagetask = new Asyncimagetask ( ImageView); Asyncimagetask.execute (path);} /** * Loading pictures asynchronously using Asynctask* * @author Administrator * */private final class Asyncimagetask extends Asynctask<string, Integer, uri> {private ImageView imageview;public asyncimagetask (ImageView ImageView) {this.imageview = ImageView;} Protected Uri doinbackground (String ... params) {//Sub-thread execution in try {return contactservice.getimage (Params[0], cache);} catch (Exception e) {E.printstacktrace ();} return null;} protected void OnPostExecute (Uri result) {//runs on the main thread if (result! = NULL && ImageView! = null) Imageview.setimageuri (r Esult);}} Asynchronously loading a picture using Handler * * private void Asyncimageload (final ImageView ImageView, final String path) * {* Final Handler ha Ndler = new Handler () {* public void * Handlemessage (Message msg) {//run in the main thread * uri uri = (uri) msg.obj; * IF (Uri!=null & amp;& imageview!= null) Imageview.setimageuri (URI); * } * }; * * Runnable Runnable = new Runnable () {* public void Run () {* Try {* URI uri = * Contactservice.getimage (path, Cache); * Handler.sendmessage (Handler.obtainmessage ((URI)); *} catch (Exception e) {* E.printstacktrace (); * } * } * }; * New Thread (runnable). Start (); *} */private Final class Datawrapper {public ImageView imageview;public TextView textview;public datawrapper (ImageView i Mageview, TextView TextView) {This.imageview = Imageview;this.textview = TextView;}}}
The above is all the code of the project, run the project as follows:
finally attach the server and client source:http://download.csdn.net/detail/wwj_748/7300567