Read data from the network and dynamically display it in listview

Source: Internet
Author: User

In the past two days, I wrote a small program, used to read XML data from the network, and displayed it in listview.

There are several key points:

  • Read data from the network
  • Parse XML using Sax
  • Asynchronously filling listview
First look: a very simple interface. For convenience, I put an XML file on my server. Its content is mainly:
<? XML version = "1.0"?> <Products> <product> <price> 100 </price> <Name> Android Dev </Name> <image src = "image/android1.png"/> </product> <Product> <price> 100 </price> <Name> androiddev2 </Name> <image src = "image/android1.png"/> </product> <! -- Repeat... --> </Products>
This program starts a new thread with asynctask to download and parse the XML. It communicates with the main thread through the handler object. Use httpget to download the XML file. In this case, the Apache package must first include the following package:
import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;
The Code is as follows: (use the get method)
Protected string doinbackground (string... params) {httpget httprequest = new httpget (Params [0]); // create an httpget object httpclient = new defaulthttpclient () from the URL; // mshowhtml. settext (""); try {httpresponse = httpclient.exe cute (httprequest); If (httpresponse. getstatusline (). getstatuscode () = httpstatus. SC _ OK) {// code used to obtain the HTTP return value httpentity entitiy = httpresponse. getentity (); inputstrea M in = entitiy. getcontent (); // get content // Parse XML. The following describes inputsource source = new inputsource (in); saxparserfactory sax = saxparserfactory. newinstance (); xmlreader = sax. newsaxparser (). getxmlreader (); xmlreader. setcontenthandler (New producthandler (); xmlreader. parse (source);} else {// return "request failed! "; // Mshowhtml. settext ("request failed"); // message mymsg = mmainhandler. obtainmessage (); // mymsg. OBJ = "request failed"; // mmainhandler. sendmessage (mymsg) ;}} catch (ioexception e) {e. printstacktrace ();} catch (saxexception e) {e. printstacktrace ();} catch (parserconfigurationexception e) {e. printstacktrace ();} return NULL ;}
Parse XML using the sax parsing method, first include the required package
import org.xml.sax.InputSource;import org.xml.sax.SAXException;import org.xml.sax.XMLReader;import org.xml.sax.helpers.DefaultHandler;

The parsed code, as shown above:

// Inputsource is the resolution source. You can use an inputstream to create inputsource source = new inputsource (in); saxparserfactory sax = saxparserfactory. newinstance (); xmlreader = sax. newsaxparser (). getxmlreader (); xmlreader. setcontenthandler (New producthandler (); // producthandler is the parsing handle xmlreader. parse (source );

Sax mainly uses the contenthandler interface to transmit good data parsing. However, more often, it uses defaulthandler.

Class producthandler extends defaulthandler {// inherit from defaulthandler to private productinfo curproduct; private string content; // call Public void startelement (string Uri, string localname, string name, org. XML. sax. attributes attributes) throws saxexception {If (localname. equals ("product") {// parse curproduct = new productinfo ();} else if (localname. equals ("image") {// Set Name curproduct. image = attributes. getvalue ("src"); // extract the image src attribute} super. startelement (Uri, localname, name, attributes);} public void endelement (string Uri, string localname, string name) throws saxexception {If (localname. equals ("product") {// when a tag is parsed, send a message, pass the product class as a parameter // send event // get main handler message MSG = mmainhandler. obtainmessage (); MSG. OBJ = curproduct; mmainhandler. sendmessage (MSG); // log. I ("product:", curproduct. tostring ();} else if (localname. equals ("name") {// Set Name curproduct. name = content; // save name} else if (localname. equals ("price") {curproduct. price = float. parsefloat (content); // save price} super. endelement (Uri, localname, name) ;}// obtain the specific content, which is the text saved under the tag public void characters (char [] CH, int start, int length) throws saxexception {content = new string (CH, start, length); // log. I ("Parser:", content); super. characters (CH, start, length );}}

The definition of the productinfo class is very simple.

    class ProductInfo {    public String name;    public float price;    public String image;    public String toString() {    return "\nName:" + name +"\nPrice :" + price + "\nImage:" + image;    }    }
Execute the above Code in asynctask
Public class gethttptask extends asynctask <string, integer, string> {public gethttptask () {} protected void onpreexecute () {// execute before entering the thread. This function is executed in the caller's thread} protected string doinbackground (string... params) {// The thread's execution subject httpget httprequest = new httpget (Params [0]); ...... // mainly execute the downloaded and parsed response? return NULL;} protected void onpostexecute (string result) {// call after completion }}

In the main thread, call the execute method of gethttptask to execute

BTN. setonclicklistener (new view. onclicklistener () {// call @ overridepublic void onclick (view V) in the oncreate function {// todo auto-generated method stubhttpget ();}});

Httpget method:

   void httpGet() {    GetHttpTask task = new GetHttpTask();    task.execute("http://192.168.1.111:8080/nfcdemo/products.xml");    }    
In the above example of asynchronous message passing, a message is sent in the endelement function. The following is the handler mhandler object that receives the message in the main activity. This is done in oncreate.
Mmainhandler = new handler () {public void handlemessage (Message MSG) {// mshowhtml. append (string) msg. OBJ); If (msg. OBJ! = NULL) {productinfo prod = (productinfo) MSG. OBJ; log. I ("prodcut:", prod. tostring (); // mshowhtml. append (prod. tostring (); hashmap <string, Object> map = new hashmap <string, Object> (); map. put ("name", prod. name); map. put ("price", "RMB" + prod. price); MList. add (MAP); // MList saves the specific list data mprodlist. notifydatasetchanged (); // mprodlist is a listview object. This function causes the listview to re-read data }}};

The main points of this process are basically the above. paste all the code! For more information about listview usage, see http://blog.csdn.net/hellogv/article/details/4542668master code:

Package COM. test. HTTP; import Java. io. ioexception; import Java. io. inputstream; import Java. util. arraylist; import Java. util. hashmap; import javax. XML. parsers. parserconfigurationexception; import javax. XML. parsers. saxparserfactory; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. httpstatus; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. me Thods. httpget; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. XML. sax. inputsource; import Org. XML. sax. saxexception; import Org. XML. sax. xmlreader; import Org. XML. sax. helpers. defaulthandler; import android. app. activity; import android. OS. asynctask; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. view; import android. wi DGET. button; import android. widget. edittext; import android. widget. listview; import android. widget. simpleadapter; public class htmltestactivity extends activity {edittext murltext; // edittext mshowhtml; listview mproducts; handler mmainhandler; simpleadapter mprodlist; arraylist Main. xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <LinearLayout        android:id="@+id/linearLayout1"        android:layout_width="match_parent"        android:layout_height="wrap_content" >        <EditText            android:id="@+id/eturl"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_weight="1" >            <requestFocus />        </EditText>        <Button            android:id="@+id/btngo"            android:layout_width="100dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="Go!" />    </LinearLayout>    <ListView        android:id="@+id/productList"        android:layout_width="match_parent"        android:layout_height="match_parent" >    </ListView></LinearLayout>
Listitem. xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <ImageView        android:id="@+id/product_icon"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentLeft="true"        android:layout_alignParentTop="true"        android:src="@drawable/ic_launcher" />    <TextView        android:id="@+id/prd_title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_toRightOf="@+id/product_icon"        android:text="TextView" />    <TextView        android:id="@+id/prd_price"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_alignParentTop="true"        android:text="TextView" /></RelativeLayout>

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.