Android-set up a simple server + ListView to load data Asynchronously

Source: Internet
Author: User
Tags delete cache

Android-set up a simple server + ListView to load data Asynchronously


May 6, 2014

This blog post will teach you how to build a server in MyEclipse, communicate with them on your mobile phone, and load data asynchronously.


I am using MyEclipse. You can also use Eclipse to create a Java Web project. The ADT Bundle provided by Google cannot create a Web project. Readers can download the Eclipse For JaveEE Developer IDE.

The following describes how to create a Web project in MyEclipse and deploy it to Tomcat. I will not talk about Tomcat configuration here.

Create a Web project named Test. The project structure is shown in:

I created an images folder and a list. xml file. The images folder stores some images, which we will obtain below. list. xml is an xml file with the following content:

<? 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 = "10"> <name> frog 10 </name> <image src = "http: // 192.192.8.233: 8080/Test/images/10.gif"/> </contact> <contact id = "11"> <name> frog 11 </name> <image src = "http: // 192.192.8.233: 8080/Test/images/11.gif"/> </contact> <contact id = "12"> <name> frog 12 </name> <image src = "http: // 192.192.8.233: 8080/Test/images/12.gif"/> </contact> <contact id = "13"> <name> frog 13 </name> <image src = "http: // 192.192.8.233: 8080/Test/images/13.gif"/> </contact> <contact id = "14"> <name> frog 14 </name> <image src = "http: // 192.192.8.233: 8080/Test/images/14.gif"/> </contact> <contact id = "15"> <name> frog 15 </name> <image src = "http: // 192.192.8.233: 8080/Test/images/15.gif"/> </contact> <contact id = "16"> <name> frog 16 </name> <image src = "http: // 192.192.8.233: 8080/Test/images/16.gif"/> </contact> <contact id = "17"> <name> frog 17 </name> <image src = "http: // 192.192.8.233: 8080/Test/images/17.gif"/> </contact> <contact id = "18"> <name> frog 18 </name> <image src = "http: // 192.192.8.233: 8080/Test/images/18.gif"/> </contact> </contacts>

We can see list. the outermost layer of xml is a contacts tag, which contains multiple sub-contact tags. Each sub-tag contains the id, name, and image content. This is the content to be parsed corresponding to each Contact object.

Here, we can see that the image Tag src is the image url address, which is the IP address of my PC. During the test, you need to change this IP address to the IP address of your PC, how to get it?Run-> cmd-> ipconfig/allCheck the ipv4 address, which is the IP address of your computer.



After creating a Web project, test it on the computer and enter the address in the browser:

Http: // 192.192.8.233: 8080/Test/list. xml



After reading the above content, we can access our server. Now we can develop our client:

Here I created a 07_DataAsyncLoad project:

The directory structure is as follows:



Set permissions in AndroidManifest. xml because of the need to connect to the Internet:

<! -- INTERNET permission --> <uses-permission android: name = "android. permission. INTERNET"/>

According to list. xml on the server, we need to define an object class:

/07_DataAsyncLoad/src/com/wwj/domain/Contact. java

Package com. wwj. domain;/*** Contact entity class ** @ author wwj **/public class Contact {public int id; public String name; public 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 contact * @ return */publ Ic static List <Contact> getContacts () throws Exception {// The 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 the timeout value to 5 seconds conn. setRequestMethod ("GET"); // sets the request method if (conn. getResponseCode () = 200) {// Code 200 return parseXML (conn. getInputStream ();} return null;}/*** use the pull parser to parse the xml file * @ p Aram xml * @ return * @ throws Exception */private static List <Contact> parseXML (InputStream xml) throws Exception {List <Contact> contacts = new ArrayList <Contact> (); contact contact = null; XmlPullParser pullParser = Xml. newPullParser (); pullParser. setInput (xml, "UTF-8"); int event = pullParser. getEventType (); // get the start Document Syntax while (event! = XmlPullParser. END_DOCUMENT) {// cyclically parse switch (event) {case XmlPullParser as long as it is not equal to the end event of the document. START_TAG: // start tag 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 (); // obtain the text value of the subsequent node} else if ("image ". equals (pullParser. getName () {contact. image = pullParser. getAttri ButeValue (0); // obtain the value of the first attribute} break; case XmlPullParser. END_TAG: // end tag if ("contact ". equals (pullParser. getName () {contacts. add (contact); // add the contact object to the set. contact = null;} break;} event = pullParser. next (); // go to the next tag} return contacts;}/*** get the network image. If the image exists in the cache, it is returned, otherwise, load the image from the network and cache it * @ param path image path * @ return */public static Uri getImage (String path, File cacheDir) throws Exception {// path-> MD5-> 32 character string. jpg F Ile 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 () == 200) {FileOutputStream outStream = new FileOutputStream (localFile); InputStream inputSt Ream = conn. getInputStream (); byte [] buffer = new byte [1024]; int len = 0; while (len = inputStream. read (buffer ))! =-1) {outStream. write (buffer, 0, len);} inputStream. close (); outStream. close (); return Uri. fromFile (localFile) ;}} return null ;}}

The above Code clearly defines how to obtain data from the server. The general process is as follows: pass a network path, open the connection through URL, connect to the server through HttpURLConnection, and get the input stream, parse the xml file and obtain the data.


The above code obtains the network image and requires MD5 encryption calculation. The specific 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 {MessageDigest digest = MessageDigest. getInstance ("MD5"); digest. update (content. getBytes (); return getHashString (digest);} catch (NoSuchAlgorithmException e) {e. printStackTrace ();} return null;}/*** obtain the hash String ** @ param digest * @ return */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 ();}}

Okay, so our service class has been written, and we load 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 Ac Tivity {ListView listView; File cache; // cache File Handler handler = new Handler () {public void handleMessage (Message msg) {listView. setAdapter (new ContactAdapter (MainActivity. 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. findVi EwById (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 a Thread to load data. new Thread (new Runnable () {public void run () {try {List <Contact> data = ContactService. getContacts (); // send the message handler through handler. sendMessage (handler. obtainMessage (22, 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 data, because network operations cannot be performed in the UI thread. After loading the data, send a message through Hanlder to display the list.


In general, we need to process images separately. There are many methods. Handler + Thread and AsyncTask are the most commonly used methods. The specific implementation is as follows:

/07_DataAsyncLoad/src/com/wwj/adapter/ContactAdapter. java

We have defined a list adapter to fill in our data. Our asynchronous image loading 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 File LayoutInflater layoutInflater; public ContactAdapter (Context context, List <Contact> data, int listviewItem, File cache) {this. data = data; this. listviewItem = listviewItem; this. cache = cache; layoutI Nflater = (LayoutInflater) context. getSystemService (Context. LAYOUT_INFLATER_SERVICE); // get the layout filling service}/*** total number of data obtained */public int getCount () {return data. size ();}/*** obtain the data corresponding to the Set Based on the data Index */public Object getItem (int position) {return data. get (position);} public long getItemId (int position) {return position;}/*** when the listView displays each entry, all call this method */public View getView (int position, View convertView, ViewGroup pa Rent) {ImageView imageView = null; TextView textView = null; if (convertView = null) {convertView = layoutInflater. inflate (listviewItem, null); // obtain the view object 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.exe cute (path );} /*** use AsyncTask to asynchronously load images ** @ author Adm Inistrator **/private final class AsyncImageTask extends AsyncTask <String, Integer, Uri> {private ImageView imageView; public AsyncImageTask (ImageView imageView) {this. imageView = imageView;} protected Uri doInBackground (String... params) {// try {return ContactService executed in the Child thread. getImage (params [0], cache);} catch (Exception e) {e. printStackTrace ();} return null;} protected void onPostExecute (Uri result) {// Run in the main thread if (result! = Null & imageView! = Null) imageView. setImageURI (result) ;}}// use Handler to asynchronously load images/** private void asyncImageLoad (final ImageView imageView, final String path) * {* final Handler handler = new Handler () {* public void * handleMessage (Message msg) {// run * Uri uri Uri = (Uri) msg in the main thread. obj; * if (uri! = Null & imageView! = Null) imageView. setImageURI (uri); *}; ** Runnable runnable = new Runnable () {* public void run () {* try {* Uri = * ContactService. getImage (path, cache); * handler. sendMessage (handler. obtainMessage (10, uri); *} catch (Exception e) {* e. printStackTrace (); *}; * new Thread (runnable ). start (); *} */private final class DataWrapper {public ImageView imageView; public TextView textView; public DataWrapper (ImageView imageView, TextView textView) {this. imageView = imageView; this. textView = textView ;}}}

The above is all the code of this project. The project running effect is as follows:



Final attached server and client source code: http://download.csdn.net/detail/wwj_748/7300567



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.