Android network programming to get XML on the network

Source: Internet
Author: User

Android network programming to get XML on the network


Please respect other people's labor results, reproduced please specify the source: Android network programming to get XML on the network

Server-side support is required to obtain XML on the network.

First, create server-side:

Server-side project structure:


Server-side operation:


First step: Create the JavaBean required for your business

Package Com.jph.server.model;import java.util.date;/** * News entity class * @author JPH * date:2014.09.26 */public class News {privat e integer id;private string title;private date publishdate;public News (Integer ID, string title, Date publishdate) {this.i D = id;this.title = Title;this.publishdate = publishdate;} Public Integer GetId () {return ID;} public void SetId (Integer id) {this.id = ID;} Public String GetTitle () {return title;} public void Settitle (String title) {this.title = title;} Public Date Getpublishdate () {return publishdate;} public void Setpublishdate (Date publishdate) {this.publishdate = Publishdate;}}

Step Two: Create a business logic interface and a concrete implementation class

Business interface:

Package Com.jph.server.service;import Java.util.list;import Com.jph.server.model.news;public interface XMLService {/ * * Get the latest information * @return */public list<news> getlastnews ();}

Implementation class for the business interface:

Package Com.jph.server.service.impl;import Java.util.arraylist;import Java.util.date;import java.util.List;import Com.jph.server.model.news;import Com.jph.server.service.xmlservice;public class Xmlservicebean implements Xmlservice {/** * get the latest video info * @return */public list<news> getlastnews () {list<news> Newes = new Arraylist<ne Ws> (); Newes.add (New News (1, "JPH", New Date (System.currenttimemillis () +100002))), Newes.add (New News (2, "admin", New Date (System.currenttimemillis () +330002)); Newes.add (New News (3, "Tom", New Date (System.currenttimemillis () + 180002))); return Newes;}}

Step three: Create a controller servlet

Package Com.jph.server.xml;import Java.io.ioexception;import Java.util.list;import javax.servlet.ServletException; Import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.jph.server.model.news;import Com.jph.server.service.XMLService Import com.jph.server.service.impl.xmlservicebean;/** * is responsible for responding to client requests: Http://xxx/ServerForXML/ServletForXMLServlet * /public class Servletforxml extends HttpServlet {private static final long Serialversionuid = 1l;private Xmlservice Newsse Rvice = new Xmlservicebean ();p rotected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doPost (request, response);} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { List<news> Newes = Newsservice.getlastnews ();//Get the latest video information Request.setattribute ("Newes", newes);// Turn the client's request to the news.jsp page request.getrequestdispatcher ("/web-inF/page/news.jsp "). Forward (request, response);} 

Fourth step: Generate an XML file using the JSTL tag

So you need to use the JSTL tag so you need to import the Jstl.jar and Standard.jar two jar packages into the project.

Use Jstl label in JSP page Generation XML:

news.jsp page:

<%@ page language= "java" contenttype= "text/xml; Charset=utf-8 "pageencoding=" UTF-8 "%><%@ taglib uri=" Http://java.sun.com/jsp/jstl/core "prefix=" C "%><? XML version= "1.0" encoding= "UTF-8"? ><newslist><c:foreach items= "${newes}" var= "News" ><news id= "${ News.id} "><title>${news.title}</title><publishdate>${news.publishdate}</publishdate ></news></c:forEach></newslist>

The server-side project has been completed. Start creating an Android -side project below.

Second, create the Android side:

Android End Project Structure:


First step: Create the JavaBean required for your business

Tips: because server-side and Android end projects are all using the Java language implementation, so some components can be shared, JavaBean is one of them. When we build the Android Project, we can fully use the JavaBean in the server-side project .

Step Two: Create the business logic layer of the Android-side project

Core code: Getxmlandparse.java:

Package Com.jph.gxfi.service;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.URL; Import Java.util.arraylist;import java.util.date;import Java.util.list;import Org.xmlpull.v1.xmlpullparser;import Com.jph.gxfi.model.news;import android.os.handler;import android.os.message;import android.util.Xml;/** * Get Xml on the network , and resolves * @author jph * date:2014.09.26 */public class Getxmlandparse {private String url= "Http://10.219.61.117:8080/ServerF Orxml/servletforxml ";p ublic static final int parsesuccwss=0x2001;private Handler handler;public getxmlandparse ( Handler Handler) {//TODO auto-generated constructor Stubthis.handler=handler;} /** * Get xml */public void GetXml () {New Thread on network (new Runnable () {@Overridepublic void Run () {//TODO auto-generated Metho D stubtry {httpurlconnection conn= (httpurlconnection) new URL (URL). OpenConnection (); conn.setconnecttimeout (5000);// Set the connection timeout Conn.setrequestmethod ("GET"), if (Conn.getresponsecode () ==200) {InputStream Inputstream=conn.getinputstream ( ); List<news> Listnews=pullxml (InputStream); if (Listnews.size () >0) {//if the resolved result is not NULL, the parsed data is sent to the UI thread message msg= New Message (); Msg.obj=listnews;msg.what=parsesuccwss;handler.sendmessage (msg);}}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Establish a connection with the server}). Start (); /** * Parse XML and encapsulate it as * @param inputstream */protected list<news> pullxml (inputstream inputstream) {list<news> Listnews=new arraylist<news> (); try {xmlpullparser pullparser=xml.newpullparser (); News news=null;pullparser.setinput (InputStream, "utf-8"); int eventcode=pullparser.geteventtype (); while (eventcode! =xmlpullparser.end_document) {String targetname=pullparser.getname (); switch (eventcode) {case Xmlpullparser.start_ Tag:if ("News". Equals (TargetName)) {//processing the start node of news news =new News (); News.setid (New Integer ( Pullparser.getattributevalue (0)));} else if ("title". Equals (TargetName)) {News.settitle (Pullparser.nexttext ());} else if ("Publishdate". Equals (TargetName)) {news.setpublishdate (new Date(Pullparser.nexttext ()));} Break;case XmlPullParser.END_TAG:if ("News". Equals (TargetName)) {//Processing the end node of news Listnews.add (news);} break;} Eventcode=pullparser.next ();//Parse Next node (Start node, end node)}} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} return listnews;}}

Step Three: Create activity

Package Com.jph.gxfi.activity;import Java.text.simpledateformat;import Java.util.arraylist;import java.util.Date; Import Java.util.hashmap;import java.util.list;import Java.util.map;import Com.jph.gxfi.r;import Com.jph.gxfi.model.news;import Com.jph.gxfi.service.getxmlandparse;import Android.os.bundle;import Android.os.handler;import Android.os.message;import Android.widget.listview;import Android.widget.SimpleAdapter; Import android.app.activity;/** * Get XML on the network * @author JPH * date:2014.09.26 */public class Mainactivity extends Activity { Private List<news>listnews;private ListView List; Handler mhandler=new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated method Stubswitch (msg.what) {case getxmlandparse.parsesuccwss:listnews= (list<news>) msg.obj;initdata (); Super.handlemessage (msg);}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); list= (ListView) findViewbyid (r.id.list); Getxmlandparse getxmlandparse=new Getxmlandparse (Mhandler); Getxmlandparse.getxml ();} /** * Populates the parsed XML into the ListView */protected void InitData () {//TODO auto-generated method Stublist<map<string, Object&gt ; >items=new arraylist<map<string,object>> (); for (News news:listnews) {map<string, Object>item= New hashmap<string, object> (), Item.put ("id", News.getid ()), Item.put ("title", News.gettitle ()), Item.put ("Time ", Convertdate (News.getpublishdate ())); Items.Add (item);} Simpleadapter adapter=new Simpleadapter (this, items, r.layout.line, new string[]{"id", "title", "Time"}, new int[]{ R.id.tvid,r.id.tvtitle,r.id.tvtime}); List.setadapter (adapter);} Private String convertdate (Date publishdate) {//TODO auto-generated method Stubsimpledateformat sdf=new SimpleDateFormat ("Yyyy-mm-dd hh-mm-ss"); return Sdf.format (Publishdate);}}

The Android project is now complete. Let's look at how the app works:

Android Run:


Android network programming to get XML on the network

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.