Sunday, June 17, 2012

Parsing Xml data and deploying into list view in android

Parsing Xml data and deploying into list view in android




Make a HTTP request to get the data from the webservice
Parse a XML document and read the contents
Make a custom ListView with the data from the webservice
On the bottom you can download the source code. But lets run through the some important parts first. So lets start on the top:

The HTTP request

We will use this URL: http://p-xr.com/xml. Its static, but you can make your own dynamic XML output by following this tutorial . The following code is the XML output:
<results count="6">
<result>
      <id>1</id>
      <name>Mark</name>
      <score>6958</score>
  </result>
  <result>
      <id>2</id>
      <name>Wesley</name>
      <score>4039</score>
  </result>
  <result>
      <id>3</id>
      <name>Roy</name>
      <score>3809</score>
  </result>
  <result>
      <id>4</id>
      <name>Mike</name>
      <score>1980</score>
  </result>
  <result>
      <id>5</id>
      <name>Tina</name>
      <score>24</score>
  </result>
  <result>
      <id>6</id>
      <name>Ike</name>
      <score>3</score>
  </result>
</results>
In Android its pretty simple to make a HTTP request:
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://p-xr.com/xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
A hard part is to actually read the XML So lets take a look there
Parse an XML document

To read an XML structure we will parse it to a Document. See the following code to learn how its done:
public Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is); 
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
Well Now we have got the data + we imported the XML structure into a Document. Lets see if we can put this into a nice ListView.
Make a custom ListView from the XML

Now we take what we learned and make a ListView with the data. The following script is a piece from the Activity and it does the following:
Extends a ListActivity
A custom ListView with 2 lines in each list item
implements a onItemClick method 
public class Main extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
//Needed for the listItems
ArrayList<hashmap<string, String="">> mylist = new ArrayList<hashmap<string, String="">>();
//Get the xml string from the server
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(Main.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
//fill in the list items from the XML document
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<string, String=""> map = new HashMap<string, String="">();  
Element e = (Element)nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("name", "Naam:" + XMLfunctions.getValue(e, "name"));
map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
mylist.add(map);
}
//Make a new listadapter
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "Score" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
//Get the listView ( from: ListActivity )
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap<string, String=""> o = (HashMap<string, String="">) lv.getItemAtPosition(position);
Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show();
}
});
}
}</string,></string,></string,></string,></hashmap<string,></hashmap<string,>
 Have fun