Android: Reading, using and working with XML data and web services in Android

Posted July 19th @ 8:37 pm by Boyan

One of the most powerful aspects of any mobile application for a 3G phone is that it can connect to the Internet. By connecting to the Internet the application can offer much more value to the user since it becomes an interface for a web-based component, e.g. using Twitter’s API to create a Twitter application so that you can get your Twitter updates without having to open the mobile browser. The most common way of interfacing with a web-based component is by using web services in XML format.

While trying to developer my own app which reads a web service from my own server, I ran into a lot of difficulties in implementing the client that consumes the web service. Android does not have libraries for XPath handling of XML documents, so it makes deciphering XML data a little bit more difficult. From what I’ve read online the Android team is currently working on including such libraries in future versions.

After some digging around I found an amazing link that shows different methods for consuming an XML file in Android and parsing through it without the use of XPaths. The link is this: Working with XML on Android. To start off, this link is an absolute must-read. Everything that I am going to write in my post here relates to this link. The code offered on that webpage uses polymorphism to show you 4 different methods of working with XML data. It provides a fully-functional Android application and all the source code for it. The source code can be found here: AndroidXML.zip.

My post today will concentrate on how to customize the code from the application in the above link, in order to read and parse your own XML data. If you are a Java pro, you might not need this post. My Java is a little rusty, so I needed some time to figure out exactly what I had to change and where in order to get this to work with my own web service XML. Now that I’ve figured it out, I thought I’d share it. In my next post I will give the simplified version of this code – where there is no polymorphism, and thus there are only the minimum number of classes needed to implement this XML-reading solution. I can’t offer this simplified code right now – because I haven’t coded it yet :).

So until I post the simplified source code for working with XML data in Android, here are some tips on getting through the larger polymorphism-based source code and customizing it for your own XML data:

1. First off, read over the link Working with XML on Android as much as you can.

2. Download the source code for the Android application that they offer: AndroidXML.zip.

3. Import the project into your Eclipse workspace by right-clicking in Project Explorer and selecting “Import”.

01 Import

4. Select “Existing Projects into Workspace”

5. Browse to the directory where you extracted the ZIP file with the source code and then click on the Next buttons to finish off the wizard. The project is called “AndroidXml”.

6. You will now see the project in your workspace:

02 project

7. Here is a quick breakdown of what some of those Java classes do:

- MessageList.java is the main activity that gets started. It lists the items from the XML data using a ListActivity. In this project the items come from an RSS feed.

- FeedParser.java, FeedParserFactory.java, BaseFeedParser.java, RSSHandler.hava are all classes that this particular example uses to set the framework for polymorphism.

- This example uses 4 methods for grabbing the XML data and reading it.The 4 methods that this example uses are:

1. AndroidSaxFeedParser.java (the default)

2. DomFeedParser.java

3. SaxFeedParser.java

4. XmlPullFeedParser.java

These 4 classes all extend BaseFeedParser.java.

8. In order to customize this for your own XML file you need to edit the following places (assuming you are using AndroidSaxFeedParser, which is the default):

- FeedParserFactory.java: you need to change the URL location of the web service or XML document in the global variable here:

static String feedUrl = "http://www.androidster.com/android_news.rss";

- AndroidSaxFeedParser.java: you need to change the root node of your XML document. This is stored in the String called RSS.

static final String RSS = "RootNode";

- BaseFeedParser.java: you need to change this class according to the nodes that your XML document has.

The nodes CHANNEL and ITEM refer to the nodes <Channel> and <Item> in the RSS feed that this example uses. You need to change them to mimic your nodes from your XML document:

static final String CHANNEL = "channel";
static final  String ITEM = "item";

The other constants that are declared refer to the nodes for each repeating item.

static final  String PUB_DATE = "pubDate";
static final  String DESCRIPTION = "description";
static final  String LINK = "link";
static final  String TITLE = "title";

For this particular example, since an RSS feed XML document is used, it has repeating nodes for <Description>, <Link>, <Title>, <PubDate>. You need to change this structure to mimic your structure.

Note: Remember that if you change the name of the constants (as opposed to the value of the constants), you will need to change other classes which call these constants.

- If you change the names of the constants, you will have to update AndroidSaxFeedParser.java in this section:

        item.getChild(TITLE).setEndTextElementListener(new EndTextElementListener(){
            public void end(String body) {
                currentMessage.setTitle(body);
            }
        });
        item.getChild(LINK).setEndTextElementListener(new EndTextElementListener(){
            public void end(String body) {
                currentMessage.setLink(body);
            }
        });
        item.getChild(DESCRIPTION).setEndTextElementListener(new EndTextElementListener(){
            public void end(String body) {
                currentMessage.setDescription(body);
            }
        });
        item.getChild(PUB_DATE).setEndTextElementListener(new EndTextElementListener(){
            public void end(String body) {
                currentMessage.setDate(body);
            }
        });

As you can see this section is hardcoded for the 4 nodes that are expected in this XML document (TITLE, LINK, DESCRIPTION, PUB_DATE). You will need to change this section and hardcode this for your own nodes.

- If you change the names of the higher-level nodes, i.e. <Channel> and <Item>, then you need to update the following section of AndroidSaxFeedParser.java:

Element itemlist = root.getChild(CHANNEL);
Element item = itemlist.getChild(ITEM);

And that is all. The customized code will use the AndroidSaxParser implementation of an XML Parser, it will go to the URL you provided in FeedParserFactory.java, and it will iterate through the updated nodes as you have labeled them in BaseFeedParser.java and AndroidSaxFeedParser.java.

In my next post I will provide a simplified version of this code, which does not use polymorphism. It will (hopefully) use the minimum required classes to get XML data and parse it.

Advertisement


-->

2 Trackbacks/Pingbacks

  1. Pingback: Android: Simplified source code for parsing and working with XML data and web services in Android | Warrior Point - Latest News & Tutorials on SaaS, Android and On-demand Software on July 20, 2009
  2. Pingback: Anybody Help me ! I got some Problem running android application using ANDROID_SAX - Android Forums on March 12, 2010

7 Comments

  1. Jon
    October 2, 2009 at 07:32

    Hi, This is a great manual, congratulations. I have a problem.

    In MessageList.java I would like pass more items to the view.

    Now is:

    for (Message msg : messages) {
    titles.add(msg.getTitle());

    ArrayAdapter adapter = new ArrayAdapter(this, R.layout.row, titles);

    And I would like pass to the view the title and date, and in row.xml, show two diferent TextView with its design.

    Thanks, sorry my English, I am Spanish.

  2. TRANG
    March 12, 2010 at 07:07

    Hi All !
    i got some problem with running my android application on actual device : (Motorola milestone droid 2.0.1) . Althoug it’s working fine on Virtual Android (I’m using Eclipse, buiding an android application about loadFeed, work with XML from internet, using ANDROID_SAX). I dont know why ? Anybody help me, thank you very much
    I got sample code from this webpage :
    http://www.warriorpoint.com/blog/2009/07/19/android-reading-using-and-working-with-xml-data-and-web-services-in-android/

  3. raqz
    April 11, 2010 at 03:37

    Hi… I tried using this tutorial to transfer a simple object of mine but unable to do so. I am sure what is going wrong and where..could some one please look at my code placed in
    http://www.sis.pitt.edu/~arazeez/xml.

    Any help would be greatly appreciated.

    Thanks,
    Raqeeb

  4. raqz
    April 11, 2010 at 03:43

    sorry.. i am unable to place my code on the server. please just send a mail to abdulraqeeb33@gmail.com, i can send across the code to you. thanks…

  5. biqut2
    May 4, 2010 at 11:21

    I am having difficulty adapting this method to my own xml output. I have successfully went through all of the code and changed the string names and it continues to work on the xml feed provided but when I change the url and the values that it is looking for it stops working. I can use any help you can give as I am still verymuch a novice at this. My xml is as follows:

    25889
    Forex UK Real
    Manually trading with custom indicators and $250 starting balance. Strategy is to use ADX crosses on various time frames for entry points and then allowing a custom EA to close out the trades with a profit and limit the risk of a trend change.
    10322997

    -16.96
    -8.48
    -0.68
    -19.9
    252.50
    500.00

    0.10
    -42.41
    205.09
    21.99
    205.09
    false

    05/04/2010 08:39
    04/11/2010 11:09
    0
    6

    Forex.com

    28288
    Basel Financial Demo
    Mini Demo account for manual trading.
    505183

    58.20
    58.20
    5.29
    150.88
    0.00
    250.00

    0.00
    145.50
    395.50
    4.98
    395.50
    true

    04/30/2010 09:34
    04/26/2010 02:35
    1
    16

    Basel Financial

    28569
    FXDD Contest Account
    This demo account is for the contest.
    7602194

    60.47
    60.46
    12.09
    325.58
    0.00
    1000.00

    -1.36
    604.64
    1604.64
    13.84
    1604.64
    true

    05/02/2010 19:54
    04/27/2010 08:26
    0
    5

    FXDD

  6. biqut2
    May 4, 2010 at 11:21

    EDIT: tags did not show up

    25889
    Forex UK Real
    Manually trading with custom indicators and $250 starting balance. Strategy is to use ADX crosses on various time frames for entry points and then allowing a custom EA to close out the trades with a profit and limit the risk of a trend change.
    10322997

    -16.96
    -8.48
    -0.68
    -19.9
    252.50
    500.00

    0.10
    -42.41
    205.09
    21.99
    205.09
    false

    05/04/2010 08:39
    04/11/2010 11:09
    0
    6

    Forex.com

    28288
    Basel Financial Demo
    Mini Demo account for manual trading.
    505183

    58.20
    58.20
    5.29
    150.88
    0.00
    250.00

    0.00
    145.50
    395.50
    4.98
    395.50
    true

    04/30/2010 09:34
    04/26/2010 02:35
    1
    16

    Basel Financial

    28569
    FXDD Contest Account
    This demo account is for the contest.
    7602194

    60.47
    60.46
    12.09
    325.58
    0.00
    1000.00

    -1.36
    604.64
    1604.64
    13.84
    1604.64
    true

    05/02/2010 19:54
    04/27/2010 08:26
    0
    5

    FXDD

  7. Richard
    June 6, 2010 at 13:23

    Hi

    The link for code download at IBM has been locked down. Could you give someone a poke over there? (if that’s possible..). If not would it be possible for you to mail me the code? I’d love to look at it within eclipse!

Leave a comment

Standard Login

Options:

Colors