Android Learning (48)--Get the XML file and parse it.

Source: Internet
Author: User


1. Create javabean based on XML format
public class News {private string Title;private string Detail;private string comment;private string imageUrl; @Overridepub Lic String toString () {return "News [title=] + title +", detail= "+ Detail +", comment= "+ comment +", imageurl= "+ imag Eurl + "]";} Public String GetTitle () {return title;} public void Settitle (String title) {this.title = title;} Public String Getdetail () {return detail;} public void Setdetail (String detail) {this.detail = detail;} Public String getcomment () {return comment;} public void Setcomment (String comment) {this.comment = comment;} Public String Getimageurl () {return imageUrl;} public void Setimageurl (String imageUrl) {this.imageurl = ImageUrl;}}


2, the method of creating parsing XML because of a lot of nodes, you need to create a list to store, at the beginning of the node to initialize the list, and assemble the objectWhen an object ends, that is, at the end of the node, the object is added to the list to parse an object node, and then continue looking for the next one to parse.
list<news> newslist;private void Parsenewsxml (InputStream is) {Xmlpullparser XP = Xml.newpullparser (); try { Xp.setinput (IS, "utf-8");//To determine the event type of the node, you can know what node int type = Xp.geteventtype () is the current node; News news = Null;while (type! = xmlpullparser.end_document) {switch (type) {case XmlPullParser.START_TAG:if ("Newslist"). Equals (Xp.getname ())) {newslist = new arraylist<news> ();} else if ("News". Equals (Xp.getname ())) {news = new News ();} else if ("title". Equals (Xp.getname ())) {String title = Xp.nexttext (); News.settitle (title);} else if ("detail". Equals (Xp.getname ())) {String detail = Xp.nexttext (); News.setdetail (detail);} else if ("comment". Equals (Xp.getname ())) {String comment = Xp.nexttext (); news.setcomment (comment);} else if ("image". Equals (Xp.getname ())) {String image = Xp.nexttext (); News.setimageurl (image);} Break;case XmlPullParser.END_TAG:if ("News". Equals (Xp.getname ())) {Newslist.add (news);} break;} After parsing the current node, move the pointer to the next node and return its event type type = Xp.next ();} for (News n:newslist) {//system.out.println (n.tostrING ()),//}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}} 


3. Get XML on the network
private void Getnewsinfo () {Thread t = new Thread () {@Overridepublic void run () {String path = "http://192.168.1.103:8080/n Ews.xml "; try {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (Conn.setreadtimeout (5000);//Send an HTTP GET request to get the corresponding code if (conn.getresponsecode () = = 200) { InputStream is = Conn.getinputstream ();//Use the pull parser to parse the stream parsenewsxml (is);}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}; T.start ();}



Core complete code
public class Mainactivity extends Activity {list<news> newslist; Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {ListView LV = (ListView) Findviewbyid (R . id.lv); Lv.setadapter (new Myadapter ());}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); Getnewsinfo ();//listview LV = (ListView) Findviewbyid (r.id.lv);////to ensure that when the adapter is set, The news XML file has been parsed//lv.setadapter (new Myadapter ());} Class Myadapter extends baseadapter{//gets the number of elements in the model layer to determine how many entries the ListView requires @overridepublic int GetCount () {//TODO Auto-generated method Stubreturn newslist.size ();} @Override//Returns a View object that appears as a ListView entry to the interface public View getView (int position, View Convertview, ViewGroup parent) {News News = Newslist.get (position); View v = null; Viewholder mholder;if (Convertview = = null) {v = view.inflate (mainactivity.this, R.layout.item_listview, null); MHolder = New Viewholder ();//encapsulates the objects of all components in the layout file into the Viewholder object mholder.tv_title = (TextView) V.findviewbyid (r.id.tv_title); mholder.tv_detail = (TextView) V.findviewbyid (r.id.tv_detail); mholder.tv_ Comment = (TextView) V.findviewbyid (r.id.tv_comment); mholder.siv = (Smartimageview) V.findviewbyid (R.ID.IV);// Encapsulates the Viewholder object into the View object V.settag (Mholder);} Else{v = Convertview;mholder = (viewholder) V.gettag ();} Set Content MHolder.tv_title.setText (News.gettitle ()) to three text boxes, MHolder.tv_detail.setText (News.getdetail ()); mholder.tv_ Comment.settext (news.getcomment () + "comment");//Give news picture ImageView set content MHolder.siv.setImageUrl (News.getimageurl ()); return v;} What components are in the layout file for class viewholder{//entries, and what properties are defined here TextView tv_title; TextView Tv_detail; TextView tv_comment; Smartimageview Siv;} @Overridepublic Object getItem (int position) {return null;} @Overridepublic long Getitemid (int position) {return 0;}} private void Getnewsinfo () {Thread t = new Thread () {@Overridepublic void run () {String path = "http://192.168.13.13:8080/n Ews.xml "; try {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) Url.openconNection (); Conn.setrequestmethod ("GET"); Conn.setconnecttimeout (); conn.setreadtimeout (5000);//Send HTTP GET request, Get the corresponding code if (conn.getresponsecode () = =) {InputStream is = Conn.getinputstream ();//Use the pull parser to parse the stream parsenewsxml (is);}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}; T.start ();} list<news> newslist;private void Parsenewsxml (InputStream is) {Xmlpullparser XP = Xml.newpullparser (); try { Xp.setinput (IS, "utf-8");//To determine the event type of the node, you can know what node int type = Xp.geteventtype () is the current node; News news = Null;while (type! = xmlpullparser.end_document) {switch (type) {case XmlPullParser.START_TAG:if ("Newslist"). Equals (Xp.getname ())) {newslist = new arraylist<news> ();} else if ("News". Equals (Xp.getname ())) {news = new News ();} else if ("title". Equals (Xp.getname ())) {String title = Xp.nexttext (); News.settitle (title);} else if ("detail". Equals (Xp.getname ())) {String detail = Xp.nexttext (); News.setdetail (detail);} else if ("comment". Equals (Xp.getname ())) {String comment = xp.nexttext (); NEWs.setcomment (comment);} else if ("image". Equals (Xp.getname ())) {String image = Xp.nexttext (); News.setimageurl (image);} Break;case XmlPullParser.END_TAG:if ("News". Equals (Xp.getname ())) {Newslist.add (news);} break;} After parsing the current node, move the pointer to the next node and return its event type type = Xp.next ();} Send a message, let the main thread set the ListView adapter, if the message does not need to carry the data, can be sent an empty message handler.sendemptymessage (1);//for (news N:newslist) {// System.out.println (N.tostring ()),//}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}






Android Learning (48)--Get the XML file and parse it.

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.