Friday, February 15, 2013

Android beginner tutorial: Part 83 - Parsing XML

In this tutorial we will learn how to read and parse an XML file in Android.

Firstly, create an XML file and put it in res/xml/ directory of the project.

My XML file is called products.xml and looks like this:

<?xml version="1.0" encoding="utf-8"?>
<catalog>
  <product name="Chair" description="Something to sit on" price="50" />
  <product name="Sofa" description="Something soft to sit on" price="100" />
  <product name="Table" description="Something to put stuff on" price="70" />
</catalog>

Now go to activity_main.xml layout file of your main Activity and add a List, which will display the items from the xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    
    <ListView android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />
    
</LinearLayout>

Now go to MainActivity.java class. This is where the magic starts - we need to load and parse the data from the XML file using a XmlPullParser object. This part is very different from AS3 or anything else I have worked with. Android's xml parser creates a row of Events which we can read and parse to create a data set of our own.

Firstly let's declare an ArrayList of Strings in the onCreate() function:

ArrayList<String> list = new ArrayList<String>();

Then we add a try...catch statement, displaying an error message using a Toast in case of an error. We try to create a new XmlPullParser object and use it to load our xml file. Using a while loop, we check each event of the parser using getEventType() to see if it doesn't equal XmlPullParser.END_DOCUMENT, which means that we're parsing until we reach the end of the document. Then we check if the event equals XmlPullParser.START_TAG and the name of the tag equals "product".

We can then add items to our list object using the add() method.

try{
XmlPullParser parser = getResources().getXml(R.xml.products);

while(parser.getEventType()!=XmlPullParser.END_DOCUMENT){
if(parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equals("product")){
list.add(parser.getAttributeValue(0) + " (" + parser.getAttributeValue(2) + ")\n" + parser.getAttributeValue(1));
}
parser.next();
}
}catch(Throwable t){
Toast.makeText(this, "Error loading XML.", Toast.LENGTH_SHORT).show();
}

After the try...catch statement, set the adapter of the list view to list.

ListView listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));

Full code:

package com.example.codeforfoodtest_two;

import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ArrayList<String> list = new ArrayList<String>();

try{
XmlPullParser parser = getResources().getXml(R.xml.products);

while(parser.getEventType()!=XmlPullParser.END_DOCUMENT){
if(parser.getEventType() == XmlPullParser.START_TAG && parser.getName().equals("product")){
list.add(parser.getAttributeValue(0) + " (" + parser.getAttributeValue(2) + ")\n" + parser.getAttributeValue(1));
}
parser.next();
}
}catch(Throwable t){
Toast.makeText(this, "Error loading XML.", Toast.LENGTH_SHORT).show();
}

ListView listView = (ListView)findViewById(R.id.listview);
listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));
}
}

Those are the basics!

Thanks for reading!

No comments:

Post a Comment