Android – SAX Parsing Example

By -
Problem: how to use SAX to parse through XML documents?

This tutorial is for the Android Novice programmer who want to learn the implementation of SAX Parser.

I have also used Custom ListView inside this tutorial for the better display of response inside the ListView.

FYI, I have defined prepareXML() function where you can write fixed XML string or inside the function you can make a webservice call and fetched XML response from server. I hope you got my idea of defining this function.

Android - SAX Parsing example

Solution:

SAXParsingActivity.java

package com.technotalkative.saxparsing;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

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

import com.technotalkative.saxparsing.adapter.myAdapter;

public class SAXParsingActivity extends Activity {
    /** Called when the activity is first created. */

	ItemList itemList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String XML = prepareXML();

       try
       {
    	   SAXParserFactory spf = SAXParserFactory.newInstance();
   		   SAXParser sp = spf.newSAXParser();
   		   XMLReader xr = sp.getXMLReader();

   		   /** Create handler to handle XML Tags ( extends DefaultHandler ) */
   		   MyXMLHandler myXMLHandler = new MyXMLHandler();
   		   xr.setContentHandler(myXMLHandler);

   		   ByteArrayInputStream is = new ByteArrayInputStream(XML.getBytes());
   		   xr.parse(new InputSource(is));
   	  }
      catch(Exception e)
      {

      }

      itemList = MyXMLHandler.itemList;

      ArrayList listItem= itemList.getItem();
      ArrayList listManu = itemList.getManufacturer();
      ArrayList listModel = itemList.getModel();
      ArrayList listCost = itemList.getCost();

      ListView lview = (ListView) findViewById(R.id.listview1);
      myAdapter adapter = new myAdapter(this, listItem, listManu, listModel, listCost);
      lview.setAdapter(adapter);
    }

    private String prepareXML()
    {
    	String strXML = ""
    		+"Computer Parts"
    		+""
    		+"     Motherboard"
    		+"     ASUS"
    		+"      P3B-F"
    		+"      123.00"
    		+"  "
    		+"  "
    		+"     Video Card"
    		+"      ATI"
    		+"     All-in-Wonder Pro"
    		+"       160.00"
    		+"   "
    		+"   "
    		+"     Sound Card"
    		+"     Creative Labs"
    		+"      Sound Blaster Live"
    		+"      80.00"
    		+"  "
    		+"  "
    		+"      inch Monitor"
    		+"     LG Electronics"
    		+"      995E"
    		+"       290.00"
    		+"   "
    		+"";

    	return strXML;
    }
}

MyXMLHandler.java

package com.technotalkative.saxparsing;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class MyXMLHandler extends DefaultHandler
{
	public static ItemList itemList;
	public boolean current = false;
	public String currentValue = null;

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub

		current = true;

		if (localName.equals("PARTS"))
		{
			/** Start */
			itemList = new ItemList();

		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		current = false;

		if(localName.equals("ITEM"))
		{
			itemList.setItem(currentValue);
		}
		else if(localName.equals("MANUFACTURER"))
		{
			itemList.setManufacturer(currentValue);
		}
		else if(localName.equals("MODEL"))
		{
			itemList.setModel(currentValue);
		}
		else if(localName.equals("COST"))
		{
			itemList.setCost(currentValue);
		}
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub

		if(current)
		{
			currentValue = new String(ch, start, length);
			current=false;
		}
	}
}

itemList.java

package com.technotalkative.saxparsing;

import java.util.ArrayList;

public class ItemList
{
	ArrayList item = new ArrayList();
	ArrayList manufacturer = new ArrayList();
	ArrayList model = new ArrayList();
	ArrayList cost = new ArrayList();

	public ArrayList getItem() {
		return item;
	}
	public void setItem(String item) {
		this.item.add(item);
	}
	public ArrayList getManufacturer() {
		return manufacturer;
	}
	public void setManufacturer(String manufacturer) {
		this.manufacturer.add(manufacturer);
	}
	public ArrayList getModel() {
		return model;
	}
	public void setModel(String model) {
		this.model.add(model);
	}
	public ArrayList getCost() {
		return cost;
	}
	public void setCost(String cost) {
		this.cost.add(cost);
	}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    
    <ListView
    	android:id="@+id/listview1"
    	android:layout_width="fill_parent"
    	android:layout_height="fill_parent">
    </ListView>
</LinearLayout>

lview_row.xml

<?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="vertical" >

    <TextView
        android:id="@+id/txtItem"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ITEM"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="#FF0000" >
    </TextView>

    <TextView
        android:id="@+id/txtManufacturer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MANUFACTURER"
        android:textAppearance="?android:attr/textAppearanceMedium" >
    </TextView>

    <TextView
        android:id="@+id/txtModel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MODEL"
        android:textAppearance="?android:attr/textAppearanceMedium" >
    </TextView>

    <TextView
        android:id="@+id/txtCost"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="COST"
        android:textAppearance="?android:attr/textAppearanceMedium" >
    </TextView>

</LinearLayout>

Download Example: https://github.com/PareshMayani/Android-SAX-Parsing

Paresh Mayani

Paresh Mayani is a lead android developer from India. Currently, He is Sr. Software engineer at InfoStretch Solutions Pvt. Ltd. He has been developing android apps since very 1st version i.e. Android 1.5, he says he has seen days and nights of Android history. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

  • wayne

    Great tutorial got me started up. If I wanted to use an xml file how would I load it inside of hard coding the xml.

    • http://pareshnmayani.wordpress.com Paresh N Mayani

      Thanx for the feedback.

      I haven’t tried this code, but i have prepared this from this tutorial:

      //load file from Assets folder
      	public String LoadFile(String fileName) throws IOException
      	{
      		//Create a InputStream to read the file into
      		InputStream iS;
      
      		 //get the application's resources
      	        resources = getResources();
      		iS = resources.getAssets().open(fileName);
      
      	    //create a buffer that has the same size as the InputStream
       	    byte[] buffer = new byte[iS.available()];
      
      	    //read the text file as a stream, into the buffer
      	    iS.read(buffer);
      	    //create a output stream to write the buffer into
      	    ByteArrayOutputStream oS = new ByteArrayOutputStream();
      	    //write this buffer to the output stream
      	    oS.write(buffer);
      	    //Close the Input and Output streams
      	    oS.close();
      	    iS.close();
      
      	    //return the output stream as a String
      		return oS.toString();
      	}
      
      • http://expertiseandroid.blogspot.com Arnaud

        This completement tutorial provided by paresh should be work :
        1. load your XML file as a String object
        2. sent the string to your parser.

        • http://www.technotalkative.com/ Paresh N. Mayani

          Yes, i have defined prepareXML() where you can define your static xml string or inside the function you can make a webservice call and fetched the XML response from the server.

          Thanx.

  • keyur

    Hey I am using this tutorial for display data in a listview from web. And then I have to select one of the item from the list view. So can you please know me how to use setOnItemClickListener() for this example..Urgently I need help.

    • http://www.technotalkative.com/ Paresh N. Mayani

      Hi Keyur,
      This example is using 4 different ArrayList to display data in ListView, as per your functionality, its better you create a List of Objects of items, and pass that selected Object to the detail activity, there after you just have to fetch values from that particular object and display it.

      Let me know if you are still confused.

  • Mesfin

    Nice tutorial. It works.
    However, I tried to get the xml from a webservice, by calling the API that generates the xml inside the prepareXML() method andit doesn’t work. Of course the problem might be in the communication channel. I used the url http://10.0.2.2:8080/webservicelocation and it doesn’t work.

    Would you mind please to tell me if you have tested it. My problem is on the url that will be assigned.

    Thanks

    • Mesfin

      After a through trial. I got the answer. I wrote webservice in PHP. I store in a wamp server in a local machine. I used http://10.0.2.2 by removing the port number. It gives me the correct result.

      Mesfin

      • http://www.technotalkative.com/ Paresh N. Mayani

        Ohh thats the silly mistake :))

  • Raj

    Paresh your tutorial helps me lots i’m new to Android but your work is more appreciable it really help me lot , i read all the comments on ur code some one also discuss you with my prob but i’m unable to do this can you suggest me the way in more elaborate form how to do this…

    keyur
    February 18, 2012 at 4:54 pm (UTC 5.5)
    Reply
    Hey I am using this tutorial for display data in a listview from web. And then I have to select one of the item from the list view. So can you please know me how to use setOnItemClickListener() for this example..Urgently I need help.

    Thanks

    • http://www.technotalkative.com/ Paresh N. Mayani

      Check this ListView tutorial and try to find ItemBean class. Here we are preparing ArrayList of objects of ItemBean class, now on clicking a particular item, we will pass that particular object (clicked position) to the destination activity. Thats it !!

      Let me know if you are still confused.

  • Arokiyaraj88

    Wow…ur example is great …chanceless …. easy to understood and work … thanks man

    • pareshmayani

      Thanx for the feedback. Hope you have shared it with others :)

      • Adarsh rai

        hello sir

        I m new in android technology .Then please tell me how i will contact u if i want to take any suggestion regardin mobile apps.

        • http://www.technotalkative.com/ Paresh Mayani

          Welcome in Android world. You can explore my site or d.android.com for learning android, still if you find any issue you can ping me on @pareshmayani .

  • Suresh

    very helpfull for me thnx man…………………………

    • http://www.technotalkative.com/ Paresh Mayani

      Welcome :)

  • DINESH M K

    Nice Example…
    If we pass an empty tag i.e. in the list of 20, the scroll view is not possible in the listview. How can we overcome this issue?

  • Srikanth Munaga

    i am getting an error on myadapter