Sie sind auf Seite 1von 22

All Topics Find tutorials, courses, and more...

Code Categories Learning Guides

ANDROID SDK

Android SDK: Build a


Simple SAX Parser
by Sashen Govender 27 Dec 2011
39 Comments

5 11

Parsing data from an XML file is a very common goal in mobile applications. This
tutorial will provide you with a hands on approach for reading XML data with a SAX
parser. SAX is an abbreviation for "Simple API for XML", and it is a very powerful
tool for reading XML.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
SAX Parser Pros and Cons
One of the biggest advantages that SAX parsers offer is a low memory footprint.
They parse each line of XML data at a time and consequently do not need to load
the entire XML document into memory prior to making the data accessible. This is a
significant boost to performance, and this really becomes visible when working with
large XML documents.

One of the disadvantages of using a SAX parser is that you must define an event-
driven API that will respond to each element as it is received. This can become
time consuming to build, but if you are willing to spend a little extra time to get it
right, the outcome will be worthwhile.

Understanding XML
XML is a means of storing and transporting data. One of the main things you will
need to know for this tutorial is the structure of an XML document. XML is made
from a series of tags, just like HTML. An example of am opening tag would be
<example> , and a complementary closing tag would be </example> . Between
these tags we will find the data contained by the example tag (also called an
element). In certain cases, we may have tags with attributes that we need to handle
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
in our SAX parser. An example of this occurring in XML would be <example
attr='value'>.

Step 1: Setting Up the Application


You will need to create a new project in Eclipse. Since we are working with XML and
will be making use of the Internet for data transfer, we need to give the application
permission to access the Internet. To do this you need to open the application's
manifest file and add this line of code at the bottom, just before the closing
</manifest> tag:

1 <uses-permission android:name=
"android.permission.INTERNET"
></uses-permission>

While you are in your manifest file you should also make your application
debuggable. This can be done by adding the following line of code in your
application tag:

1 android:debuggable=
'true'

Now that the application has access to the Internet and is debuggable, we can

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
begin implementing the SAX parser.

Step 2: Creating Classes and UI


First, you will need to create three classes. The first class that should be created
when you created the project will be your activity. In this activity, all the data
retrieved will be used and displayed to the screen. The second class required will
be the handler, in this class all the extracting and setting of data will be done. The
third class will contain all the getters and setters that we need to set the data and
retrieve it.

The main.xml in your resource folder should be modified as shown below:

01 <?xml version="1.0" encoding="utf-8"?>


02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android
03 android:layout_width="fill_parent"
04 android:layout_height="fill_parent"
05 android:orientation="vertical"
06 android:id="@+id/layout">
07
08 <TextView
09 android:layout_width="fill_parent"
10 android:layout_height="wrap_content"
11 android:text="@string/hello"

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
11 android:text="@string/hello"
12 android:textSize="15dp"
13 android:gravity="center_horizontal"
14 android:id="@+id/layout_string"
/>
15
16 </LinearLayout>

Step 3: The Content Handler


The content handler is where we need to handle each of the incoming events from
the XML. So, basically what the content handler will do is read through the XML
until it reaches the end.

When an opening tag such as <example> is reached, the startElement handler


will be called. When closing tags such as </example> is reached, a closing method
called endElement gets called. When the SAX parser reaches the closing tags, it
calls a method called characters which will get all the content that is between the
opening and closing tags.
We have a String that is called elementValue, which is set to null. Each time the
parser goes through to start an end tag, we will set the elementValue string to the
data in between those tags.
We will also make use of a Boolean value called elementOn. We use this to keep
track of where the XML is being passed, so that when a tag is finished being read
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
and data has been extracted, we set it to false so that we can read the next tag in
the XML.

We have if statements to check when we reach a specific tag in order to use setters
to set the data to an array list, so that we can display it later.

Below is the sample code used in the content handler:

01 package com.android.SAXParser;
02 import org.xml.sax.Attributes;
03 import org.xml.sax.SAXException;
04 import org.xml.sax.helpers.DefaultHandler;
05
06 public class XMLHandler extends DefaultHandler {
07
08 String elementValue =null;
09 Boolean elementOn =false;
10 public static XMLGettersSetters data =null;
11
12 public static XMLGettersSetters getXMLData() {
13 return data;
14 }
15
16 public static void setXMLData(XMLGettersSetters data) {
17 XMLHandler.data = data;
18 }
19
20 /**

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
20 /**
21 * This will be called when the tags of the XML starts.
22 **/
23 @Override
24 public void startElement(String uri, String localName, String qName,
25 Attributes attributes)throws SAXException {
26
27 elementOn = true;
28
29 if (localName.equals(
"CATALOG"))
30 {
31 data = new XMLGettersSetters();
32 } else if (localName.equals(
"CD")) {
33 /**
34 * We can get the values of attributes for eg. if the CD tag had an at
35 * we can get the value "band". Below is an example of how to achieve
36 *
37 * String attributeValue = attributes.getValue("attr");
38 * data.setAttribute(attributeValue);
39 *
40 * */
41 }
42 }
43
44 /**
45 * This will be called when the tags of the XML end.
46 **/
47 @Override
48 public void endElement(String uri, String localName, String qName)
49 throws SAXException {
50
51 elementOn = false;
52

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
52
53 /**
54 * Sets the values after retrieving the values from the XML tags
55 * */
56 if (localName.equalsIgnoreCase(
"title"))
57 data.setTitle(elementValue);
58 else if (localName.equalsIgnoreCase(
"artist"))
59 data.setArtist(elementValue);
60 else if (localName.equalsIgnoreCase(
"country"))
61 data.setCountry(elementValue);
62 else if (localName.equalsIgnoreCase(
"company"))
63 data.setCompany(elementValue);
64 else if (localName.equalsIgnoreCase(
"price"))
65 data.setPrice(elementValue);
66 else if (localName.equalsIgnoreCase(
"year"))
67 data.setYear(elementValue);
68 }
69
70 /**
71 * This is called to get the tags value
72 **/
73 @Override
74 public void characters(char[] ch, int start, int length)
75 throws SAXException {
76
77 if (elementOn) {
78 elementValue = new String(ch, start, length);
79 elementOn = false;
80 }
81
82 }
83
84 }

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
In the startElement I have included a comment to show how to retrieve the
attribute of an opened tag.

Step 4: Getters, Setters, and Logcat


This is a very simple class which contains arraylists, getters and setters. Here the
array lists are set from the content handler class by calling their respective setter
methods.

In this example, it is simple because we are basically retrieving string types.


However, in other XML files you may need to retrieve other types, such as date or
URL, and you will need to make adjustments as needed. Take date for example:
you might have to use a date formatter to format the date correctly before you set it.

In each of the setter methods I have added logs like the one below:

1 Log.i('This is the value:'


, example);

This is very useful as you can use the Logcat that is located in the DDMS
perspective to track all the data that you are retrieving for the XML. A great
advantage of doing this is that if your code fails, you will know exactly at which tag
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
advantage of doing this is that if your code fails, you will know exactly at which tag
the parser is failing and can make the necessary adjustments.

Below is a snippet of code from the getters and setters class showing just one of
the getter and setter methods:

1 public class XMLGettersSetters {


2 private ArrayList<String> company =new ArrayList<String>();
3 public ArrayList<String> getCompany() {
4 return company;
5 }
6 public void setCompany(String company) {
7 this.company.add(company);
8 Log.i("This is the company:"
, company);
9 }

Below is an image of Logcat showing all the retrieved data.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Advertisement

Step 5: Displaying the Retrieved Data


In the activity, we will need to create an instance of the SAX parser. We also need
to create the handler for each of the XML tags. We also have the URL of the XML
that we need to pass into the Handler. Here is the code used to implement this:

01 try {
02 /**
03 * Create a new instance of the SAX parser
04 **/
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
04 **/
05 SAXParserFactory saxPF = SAXParserFactory.newInstance();
06 SAXParser saxP = saxPF.newSAXParser();
07 XMLReader xmlR = saxP.getXMLReader();
08
09
10 URL url = new URL("http://www.xmlfiles.com/examples/cd_catalog.xml
11
12 /**
13 * Create the Handler to handle each of the XML tags.
14 **/
15 XMLHandler myXMLHandler =new XMLHandler();
16 xmlR.setContentHandler(myXMLHandler);
17 xmlR.parse(new InputSource(url.openStream()));
18
19 } catch (Exception e) {
20 System.out.println(e);
21 }

The final step is to display the data to an Activity. For each data category we need
to create a different TextView array. For example:

1 TextView example[];

By doing this, we will be able to add all the retrieved data to these TextViews. We
need to make the length of the TextView the size of the TextView, the following line
of code will set the TextView length to the size of the TextView array:

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
1 example = new TextView[data.getExample().size()];

We need to get the layout of the Activity in order to set all the TextViews that are
created for it programmatically. Using a view we can do this simply. Below is the
line of code we require:

1 View layout = findViewById(R.id.layout);

Now that we have the length of the TextView, we can simply run a for loop to add
the data to these TextViews. The for loop will end when the end of the TextView
array is reached.

Here is the code used to implement the for loop to set the data to TextViews and
then set the TextViews to the layout:

01 for (int i = 0; i < data.getExample().size(); i++) {


02
03 example[i] = new TextView(this);
04 example[i].setText("Example= "+data.getExample ().get(i));
05
06 example2[i] = new TextView(this);
07 example2[i].setText("Example2 ="+data.get Example2().get(i));
08
09 ((ViewGroup) layout).addView(example[i]);
10 ((ViewGroup) layout).addView(example2[i]);
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
10 ((ViewGroup) layout).addView(example2[i]);
11 }

The last line of code would be used to set the layout:

1 setContentView(layout);

Conclusion
Now that everything is set up properly, you can run your app. The results should
look like the image below. If you do get an error, the most likely reason would be
that you are not handling the XML correctly. The best way to approach debugging
that is by using the Logcat.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Advertisement

Difficulty: Suggested Tuts+ Course


Intermediate
Length:
Short
Categories:

Android SDK Mobile Development

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Translations Available:

Tuts+ tutorials are translated by our community


members. If you'd like to translate this post into
Multi-Platform Apps In C# With $15
another language, let us know! Xamarin

Download Attachment
Related Tutorials

Create a YouTube Client on Android


Code

About Sashen Govender


Sashen Govender is a Senior Mobile
Developer at Net1 Mobile Solutions, a
Use Text-to-Speech on Android to
company that specializes in mobile and Read Out Incoming Messages
web development in South Africa. Code

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Create a Weather App on Android
Code

Jobs

Web Developer / Site Management


at Zanes Law in Phoenix, AZ, USA

Advertisement
PHP Coder with Magento Knowledge
at Yoginet Web Solutions in New Delhi,
Delhi, India

Envato Market Item

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Advertisement

18,890 Tutorials 461 Video Courses


Teaching skills to millions worldwide.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Follow Us Email Newsletters

Get Tuts+ updates, news, surveys &


offers.

Help and Support Email Address

FAQ
Subscribe
Terms of Use
Contact Support Privacy Policy
About Tuts+
Advertise
Teach at Tuts+

Custom digital services like logo design, WordPress installation, video


production and more.
Check out Envato Studio

Build anything from social networks to file upload systems. Build faster
with pre-coded PHP scripts.
Browse PHP on CodeCanyon

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
2014 Envato Pty Ltd. Trademarks and brands are the property of their respective
owners.

open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com

Das könnte Ihnen auch gefallen