Beruflich Dokumente
Kultur Dokumente
ANDROID SDK
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'>.
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.
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>
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.
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.
In each of the setter methods I have added logs like the one below:
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:
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
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:
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:
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
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Translations Available:
Download Attachment
Related Tutorials
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
Advertisement
PHP Coder with Magento Knowledge
at Yoginet Web Solutions in New Delhi,
Delhi, India
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Advertisement
open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com
Follow Us Email Newsletters
FAQ
Subscribe
Terms of Use
Contact Support Privacy Policy
About Tuts+
Advertise
Teach at Tuts+
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