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

Posted July 19th @ 8:37 pm by Boyan Tsolov

Advertisement

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


-->

4 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
  3. Pingback: My first learning log for developing android apps « Michelle Melkman Broadcast blog on January 31, 2011
  4. Pingback: Access Webservice from Android « Prayag Upd on August 8, 2011

25 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!

  8. Sang Shin
    August 13, 2010 at 10:00

    My name is Sang Shin. I am the founder and chief instructor of JavaPassion.com.

    I am wondering if I can use this code as part of my Android programming course. Your name will be mentioned as part of the course material.

    Thanks.

    -Sang

  9. OneWorld
    August 19, 2010 at 06:27

    Is the parsing process really that slow? I discovered times between 0,6 and 3,5 seconds depending on the parsing engine. But sounds still very slow to me. Do u guys have same delays?

  10. Tom
    September 30, 2010 at 03:25

    I want to push XML data from Android to a web service

  11. Peter
    November 7, 2010 at 20:24

    I can’t live without android at this point.

  12. dorian
    January 10, 2011 at 02:49

    how to parse the XML node with namespaces?

  13. Rohit
    March 2, 2011 at 08:08

    Hi, really very nice tutorial.
    My question is-how to get images from the rss feed xml file and display it in our android application of rss reader.
    please rply in rohitmud@gmail.com

    Thanks in advance

  14. Chintan Gupta
    May 9, 2011 at 08:11

    Hi,i am getting response from a web service in XSLT format.
    Please help me to parse data in a Listview.
    like full result list view
    TotalApplicants=152
    session_name=test1
    start_date=2011-04-11T00:00:00+01:00

    code——————–

    package com.webservice;

    import org.ksoap2.SoapEnvelope;
    import org.ksoap2.serialization.SoapObject;
    import org.ksoap2.serialization.SoapPrimitive;
    import org.ksoap2.serialization.SoapSerializationEnvelope;
    import org.ksoap2.transport.AndroidHttpTransport;

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

    public class WebService extends Activity
    {
    /* private static final String SOAP_ACTION = “http://tempuri.org/Ilogin/Logincheck”;
    private static final String METHOD_NAME = “Logincheck”;
    private static final String NAMESPACE = “http://tempuri.org/”;
    private static final String URL = “http://122.248.245.146:8090/login.svc?wsdl”;*/

    private static final String SOAP_ACTION =”http://tempuri.org/Isessions/open”;
    private static final String METHOD_NAME = “open”;
    private static final String NAMESPACE = “http://tempuri.org/”;
    private static final String URL =”http://122.248.245.146:8090/sessions.svc?wsdl”;

    /*private static final String SOAP_ACTION =”http://tempuri.org/Isessions/close”;
    private static final String METHOD_NAME = “close”;
    private static final String NAMESPACE = “http://tempuri.org/”;
    private static final String URL =”http://122.248.245.146:8090/sessions.svc?wsdl”;*/

    TextView tv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tv =(TextView)findViewById(R.id.textView1);
    SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);

    //SoapObject

    Request.addProperty(”name”, “priyanka”);
    Request.addProperty(”passcode”, “employer2″);
    //Request.addProperty(”logging”,”YES”);
    Request.addProperty(”status”, 1);
    //Request.addProperty(”status”, 0);

    SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    soapEnvelope.dotNet=true;
    soapEnvelope.setOutputSoapObject(Request);

    tv.setText(”Status0 :”);

    AndroidHttpTransport abt = new AndroidHttpTransport(URL);
    try
    {
    abt.call(SOAP_ACTION, soapEnvelope);
    //SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
    // SoapObject resultString = ((SoapObject)soapEnvelope.getResponse());
    // System.err.println(resultString.getName());
    tv.setText(”Status1 :” + soapEnvelope.getResponse());
    }
    catch (Exception E)
    {
    E.printStackTrace ();
    }
    }
    }

  15. crysty
    July 30, 2011 at 18:14
  16. krish
    August 30, 2011 at 03:14

    what is the use of default handler in this above example application?

  17. Pamila Spagnuolo
    September 30, 2011 at 08:09

    Awesome post, wish I could come up with stuff like that for my forum, hahaha.

  18. mamatha
    October 31, 2011 at 03:24

    Hai i done webservices in net.I want to pass those webservices in android by using json but i m not getting values in android.Please help me

  19. Satish
    November 9, 2011 at 05:13

    This is awesome!! thanks for sharing with us. you may check out this following url for brief knowledge on how to create android application using XML…
    http://mindstick.com/Articles/b14ad2c6-2521-41c5-bb17-f98a872ee127/?Creating%20an%20Android%20Application%20by%20using%20XML%20Layout

    Thanks !!!

  20. durgesh pathak
    November 11, 2011 at 07:41

    i am new to android please help me how can i feed news from mashable.com after importing androidxml simple file i am gettimg error my emailid is durgeshpathakk@gmail.com

  21. Endy
    December 2, 2011 at 18:57

    Thank you very much. If you do not mind, will translate the article into my native language

  22. Vldzlpae
    December 6, 2011 at 07:49

    The manager Nymphet Preteen
    =-)

  23. Dien Trinh
    December 21, 2011 at 23:33

    Hi, Thanks for your tutorial. I have a question want to ask you. How can I get url link from enclosure tag?
    Best Regards

  24. Dina
    December 29, 2011 at 23:47

    How to parse the XML node with namespaces?

  25. Levon
    January 2, 2012 at 11:52

    Hello, thanks for your post! Its realy helpful!

Leave a comment

Standard Login

Options:

Colors

  • bea test
  • vince young uncle rico
  • chicago bears 96
  • tea party hobbits
  • tea party agenda
  • checkers
  • bengals youth jerseys
  • hijack
  • contactor
  • zara phillips wedding date
  • connecticut renaissance faire
  • bengals usa
  • search engines for jobs
  • search engines zuula
  • chicago bears garter
  • la ink season 6
  • zara phillips facebookzara phillips gossip
  • zara phillips guest list
  • damon
  • dist 95
  • bea 4603
  • connecticut 100 club
  • compared
  • dreamweaver
  • new england patriots underwear
  • c span kozol
  • la ink yahoo answers
  • search in vi
  • msnbc
  • tea party nj
  • chad ochocinco height and weight
  • dues
  • vince young endorsementsvince young foundation
  • mcmillan
  • bengals tryouts
  • battleship aurora
  • trademark
  • search 3 bodybuilding other index
  • chad ochocinco quits football
  • search engines visibility
  • di's hallmark
  • 1904
  • formal
  • regions
  • carrollton
  • mtv oddities
  • vince young injury
  • bengals cheerleaders tryouts 2011
  • freida pinto chanel
  • zara phillips and the queen
  • zara phillips shoes royal wedding
  • barns
  • vince young rumors
  • chad ochocinco wedding date
  • freida pinto dev
  • vince young jay cutler
  • sqlserver
  • 4pm cspancspan area 51cspan 90.1
  • connecticut state parks
  • bengals hard knocks episode 1
  • chad ochocinco to patriots
  • search engines images
  • connecticut sun
  • chad ochocinco age
  • la ink tattoos
  • achievements
  • battleship history
  • chad ochocinco bears
  • chad ochocinco yesterday
  • goto
  • search 5500
  • hp support englandhp support forum
  • battleship galactica
  • connecticut 5 star resorts
  • bengals 08 schedule
  • vince young 2008
  • randy moss university
  • bengals images
  • bengals cats for sale
  • la ink 105
  • benelli
  • search engines rankings 2011
  • chicago bears tattoos
  • connecticut post
  • chad ochocinco free agent
  • giro
  • la ink map
  • chad ochocinco yesterday
  • search engines internet
  • chicago bears 17 lisa lampanelli
  • recommended
  • hp support error 1005
  • hp support number united states
  • la ink youtube pixie
  • chicago bears 08 record
  • thinking
  • greg olsen puzzles
  • fireworks
  • c span video contest
  • hp support helpline
  • safeway
  • chicago bears 08 record
  • mortage
  • fight
  • workout
  • 1983
  • hp support center
  • connecticut natural gas
  • search cfisd.net
  • greg olsen vikingsgreg olsen wife
  • c span yesterdayc span zelaya
  • barn
  • bengals games
  • new england patriots 50
  • bea fox
  • mtv music awards
  • mtv website
  • dohc
  • c span 4 to 5
  • greyhound
  • projections
  • rico
  • bengals job fair
  • search engines 9
  • zara phillips wedding plans
  • cuties
  • vince young 99 yard video
  • courts
  • battleship bismarck wreck
  • dis windsor wi
  • tea party chicago
  • bea oracle
  • paco
  • dis quand reviendras-tu
  • mtv 90s music videos
  • search and seizure
  • randy moss 98 vikings
  • freida pinto miral
  • mtv 5 cover
  • mtv 2 schedule
  • search 2.0
  • bea karp
  • anemometer
  • chad ochocinco vs skip bayless
  • hp support contact us
  • vince young released
  • mtv true life
  • new england patriots jake locker
  • bea goldfishberg
  • battleship 3d game
  • la ink games online
  • bea luna
  • chicago bears tickets
  • freida pinto zac posen
  • battleship yamato 2010
  • chicago bears zip hoodie
  • tea party obama
  • greg olsen vancouver
  • new england patriots espn blog
  • search engines usage statistics 2010
  • bea 71 16
  • chicago bears football club
  • la ink 03x05
  • zara phillips baby
  • quartz
  • bea nipa
  • bea 71 series staples
  • randy moss jail
  • hp support venezuela
  • dis x
  • freida pinto boyfriend
  • copa
  • bea spells a lot
  • blade
  • zara phillips school
  • booster
  • wrist
  • greg olsen combine
  • vince young uncle rico gif
  • zara phillips royal wedding picture
  • zara phillips engagement ring
  • hp support repair
  • mtv overdrive
  • vince young yahoo stats
  • new england patriots 98.5
  • hp support 6500a plus
  • new england patriots store
  • search protocol host
  • greg olsen puzzles
  • dialup
  • mixed
  • greg olsen football