Getting started with Android: communicates with the server through XML data

Source: Internet
Author: User


1. Communicate with the server

Similar to communication between browsers and servers, Android applications can also communicate with Web servers. For example, Android applications can access Servlet, JSP, and images;
By specifying Content-Type, the Web server can specify the Type of returned data. For example, text/html indicates a webpage, text/xml indicates XML data, and image/jpeg indicates an image;

2. Use XML to allow the client to communicate with the server

 


For example, when the Android client opens the dating network, it returns a sequence of multiple people, including the person's name, age, and other information. How can we organize the data to be returned to the client? Easy to use XML;

 

Iii. Code Implementation

The server uses dom4j to organize XML data and returns it to the client;

The code structure is as follows:

 

 

[Java]
Package org. xiazdong. servlet;
 
Import java. io. IOException;
Import java. util. ArrayList;
Import java. util. List;
 
Import javax. servlet. ServletException;
Import javax. servlet. annotation. WebServlet;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
 
Import org. dom4j. Document;
Import org. dom4j. DocumentHelper;
Import org. dom4j. Element;
Import org. xiazdong. domain. Person;
 
 
@ WebServlet ("/ListServlet ")
Public class ListServlet extends HttpServlet {
Private static final long serialVersionUID = 1L;
 
Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DoPost (request, response );
}
 
Protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List <Person> list = new ArrayList <Person> ();
For (int I = 0; I <4; I ++ ){
Person person = new Person (I, "xiazdong-" + I, 20 + I );
List. add (person );
}
Document document = incluenthelper. createDocument ();
Element persons = incluenthelper. createElement ("persons ");
Document. add (persons );
For (int I = 0; I <4; I ++ ){
Persons. addElement ("person"). addattriement ("id", list. get (I). getId () + "");
Persons. addElement ("name"). addText (list. get (I). getName ());
Persons. addElement ("age"). addText (list. get (I). getAge () + "");
}
String xml = document. asXML (); // use dom4j to organize an XML String
Response. setContentType ("text/xml; charset = UTF-8"); // set the type of the returned value
Response. getOutputStream (). write (xml. getBytes ("UTF-8"); // set the return value
}
 
}


If the browser is accessed, the effect is as follows:

(Note: The XML declaration is always not displayed when Chrome is opened. Open it with IE)


Next, we can develop the client to display the data in the list;

Add the following to AndroidManifest. xml:

[Html]
<Uses-permission android: name = "android. permission. INTERNET"/>

The layout of each item is as follows:

[Html]
<? Xml version = "1.0" encoding = "UTF-8"?>
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
Android: orientation = "horizontal">
 
<TextView
Android: layout_width = "50dp"
Android: layout_height = "wrap_content"
Android: id = "@ + id/id"
/>
<TextView
Android: layout_width = "100dp"
Android: layout_height = "wrap_content"
Android: id = "@ + id/name"
/> <TextView
Android: layout_width = "50dp"
Android: layout_height = "wrap_content"
Android: id = "@ + id/age"
/>
 
</LinearLayout>

 

MainActivity. java

[Java]
Package org. xiazdong. personlist;
 
Import java. io. InputStream;
Import java.net. HttpURLConnection;
Import java.net. URL;
Import java. util. ArrayList;
Import java. util. HashMap;
Import java. util. List;
Import java. util. Map;
 
Import org. xiazdong. domain. Person;
Import org. xmlpull. v1.XmlPullParser;
 
Import android. app. Activity;
Import android. OS. Bundle;
Import android. util. Log;
Import android. util. Xml;
Import android. widget. ListView;
Import android. widget. SimpleAdapter;
 
Public class MainActivity extends Activity {
Private ListView listView;
 
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
ListView = (ListView) this. findViewById (R. id. listview );
List <Person> persons = null;
Try {
Persons = getXMLData ();
} Catch (Exception e ){
E. printStackTrace ();
}
List <Map <String, Object> maps = new ArrayList <Map <String, Object> ();
For (Person person: persons ){
HashMap <String, Object> map = new HashMap <String, Object> ();
Map. put ("id", person. getId ());
Map. put ("name", person. getName ());
Map. put ("age", person. getAge ());
Maps. add (map );
}
SimpleAdapter adapter = new SimpleAdapter (this, maps, R. layout. item,
New String [] {"id", "name", "age"}, new int [] {R. id. id,
R. id. name, R. id. age });
ListView. setAdapter (adapter );
}
 
// Read XML data and convert it to List <Person>
Private List <Person> getXMLData () throws Exception {
List <Person> persons = new ArrayList <Person> ();
Person person = null;
URL url = new URL ("http: // 192.168.0.103: 8080/Server/ListServlet ");
HttpURLConnection conn = (HttpURLConnection) url. openConnection ();
Conn. setRequestMethod ("GET ");
If (conn. getResponseCode () = 200 ){
InputStream in = conn. getInputStream ();
XmlPullParser parser = Xml. newPullParser ();
Parser. setInput (in, "UTF-8 ");
Int event = parser. getEventType ();
While (event! = XmlPullParser. END_DOCUMENT ){
Log. I ("start_document", "start_document ");
Switch (event ){
Case XmlPullParser. START_TAG:
If ("person". equals (parser. getName ())){
Person = new Person ();
Person. setId (Integer. parseInt (parser. getAttributeValue (0 )));
}
If ("name"). equals (parser. getName ())){
Person. setName (parser. nextText ());
}
If ("age". equals (parser. getName ())){
Person. setAge (Integer. parseInt (parser. nextText ()));
}
Break;
Case XmlPullParser. END_TAG:
If ("person". equals (parser. getName ())){
Persons. add (person );
Log. I ("person", person. toString ());
}
Break;
}
Event = parser. next ();
}
}
Return persons;
 
}
}

The effect is as follows:

 

Author: xiazdong

 

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.