Android tutorial: How to parse/read XML data into Android ListView
In part 2 of our serie we will talk a bit about importing and parsing XML data into a Android ListView. We will cover the following points:
- Make a HTTP request to get the data from the webservice
- Parse a XML document and read the contents
- Make a custom ListView with the data from the webservice
On the bottom you can download the source code. But lets run through the some important parts first. So lets start on the top:
The HTTP request
We will use this URL: http://p-xr.com/xml. Its static, but you can make your own dynamic XML output by following this tutorial . The following code is the XML output:
<results count="6"> Â <result> Â <id>1</id> Â <name>Mark</name> Â <score>6958</score> Â </result> Â <result> Â <id>2</id> Â <name>Wesley</name> Â <score>4039</score> Â </result> Â <result> Â <id>3</id> Â <name>Roy</name> Â <score>3809</score> Â </result> Â <result> Â <id>4</id> Â <name>Mike</name> Â <score>1980</score> Â </result> Â <result> Â <id>5</id> Â <name>Tina</name> Â <score>24</score> Â </result> Â <result> Â <id>6</id> Â <name>Ike</name> Â <score>3</score> Â </result> </results>
In Android its pretty simple to make a HTTP request:
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://p-xr.com/xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
A hard part is to actually read the XML
So lets take a look there
Parse an XML document
To read an XML structure we will parse it to a Document. See the following code to learn how its done:
public Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
Well
Now we have got the data + we imported the XML structure into a Document. Lets see if we can put this into a nice ListView.
Make a custom ListView from the XML
Now we take what we learned and make a ListView with the data. The following script is a piece from the Activity and it does the following:
- Extends a ListActivity
- A custom ListView with 2 lines in each list item
- implements a onItemClick method
public class Main extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
//Needed for the listItems
ArrayList> mylist = new ArrayList>();
//Get the xml string from the server
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(Main.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
//fill in the list items from the XML document
for (int i = 0; i < nodes.getLength(); i++) {
HashMap map = new HashMap();
Element e = (Element)nodes.item(i);
map.put("id", XMLfunctions.getValue(e, "id"));
map.put("name", "Naam:" + XMLfunctions.getValue(e, "name"));
map.put("Score", "Score: " + XMLfunctions.getValue(e, "score"));
mylist.add(map);
}
//Make a new listadapter
ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.main,
new String[] { "name", "Score" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
//Get the listView ( from: ListActivity )
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView> parent, View view, int position, long id) {
@SuppressWarnings("unchecked")
HashMap o = (HashMap) lv.getItemAtPosition(position);
Toast.makeText(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_LONG).show();
}
});
}
}
Questions or problems? Post a comment and ill try to help you a.s.a.p
. Have fun
Download: Source code / Eclipse project
Related posts:
- Android tutorial series: From SQL/ PHP to XML/ JSON to Android ListView!
- Android tutorial: Simple (but persistent) data storage with SQLite
- Tutorial: How to make a simple PHP webservice?
Google +1! this

Past codings
Tag cloud
A penny for my thoughts
Like the tuts?
Buy me a beer ;-)
Topics
- Android news
- Android tutorials
- Javascript / Ajax
- Other programming stuff :)
- PHP / HTML
- Project spotlight

December 28th, 2011 - 00:33
Hi,
very nice tutorial
January 4th, 2012 - 05:10
hi nice
January 4th, 2012 - 07:55
hello,
your tutos are really nice…they are very helpful.i preferred same code for my dummy application and trying to access my xml file from http://localhost/amol/demo.xml but it not showing errors but also it not displaying the content present in my xml so,please help me…
thank you.
January 6th, 2012 - 17:45
Very nice tutorial…but I’ve got one question. I created the XML myself (didn’t pull from a database, webpage, etc.). Is it possible to use this to create my list for my listview? Basically, I have 2 XML pages – one is a list of terms and abbreviations and their definitions and the other is a list of values and the formulas used to derive them. I want my List to be comprised of the Terms/Abbreviations and when selected to show the definition. Same with the formulas. Can you point me in the right direction?
January 8th, 2012 - 17:37
Hello,
first, thank you for great tutorial.
I was wondering if you could help me a bit?
I’m trying to parse my own XML, but I’m having some troubles.
I changed only few lines of code:
HttpPost httpPost = new HttpPost(“93.103.182.202/orders.xml”);
NodeList nodes = doc.getElementsByTagName(“order”);
map.put(“name”, “Naam:” + XMLfunctions.getValue(e, “Customer_Name”));
map.put(“score”, “Score: ” + XMLfunctions.getValue(e, “Customer_Address”));
Any ideas why I’m getting error when I start application?
Thanks.
January 8th, 2012 - 19:09
Hi and thx for this tutorial. It’s exactly what I was looking for and didn’t find anywhere else. I’m having one problem though. I don’t think it’s firing off the HttpPost and/or the HttpResponse.
Everything compiles just fine in Eclipse, and I can deploy the app to my actual phone via USB debugging. However, when I fire up the app on my device it goes directly to the “No Results Found” (line 18 of your Main class above). This happens far too quickly for it to actually send a request and wait for a response. It’s as if the HttpPost isn’t getting called at all. I checked the response from my own website and it is returning a proper XML string/file, so that’s not the issue.
Can you offer any insight into how I might resolve this?
Many thanks again!
January 11th, 2012 - 04:45
Hello Mark and thank you for you wonderful tutorials!
Your example of how to parse an rss has been very helpful to me, but I encountered a problem with the rss I’m trying to parse.The problem is that the rss contains its text between a CDATA tag which comes right after the main Tags (title, description, etc). I tried a bunch of parsing methods and yours i the only one that doesn’t end with an NullPointerException Force Close!
Can you help me with the modifications needed on the code in order to parse the CDATA section of the rss? I’m close to desperation right now!
The rss is this one: http://www.cs.teilar.gr/CS/rss.jsp
PS:It’s in Greek..sorry about that!
But if you see the page source, you should see were my problem residues!
January 11th, 2012 - 11:27
HI, your tutorial is great, but I can’t parse tags that have CDATA. could you help?
January 12th, 2012 - 04:51
Hello very nice tutorial, one thing I do not understand ( well more but that because I’m just learning java )
in
NodeList nodes = doc.getElementsByTagName(“result”);
you will get number of elements with name “result” does that count the as one ?
I’m trying to make small project and learn java for android in process but I hit a wall for me, even though this tutorial was a lot of help I still have questions about how could I apply it to what I have ( parsing similar XML to sqlitle )
Maybe if you have some time we could go over it by mail ?
Regards,
Vlad
January 12th, 2012 - 06:07
Hi, thanks for the excellent tutorial. Just one question, if the XML had a field like so:
1
Mark
6958
http://url_to_image/photo_of_mark.png
Is it possible to display Marks photo in the list?
January 17th, 2012 - 15:16
Hi, have you tried this approach using xml adapters? http://developer.android.com/resources/samples/XmlAdapters/index.html
January 25th, 2012 - 03:22
Hi,
Thanks for the good tutorial, it was very helpful. The only “problem”, or lets say observation with this, is the XML you gave is not an XML. It’s a plain string. And this is the reason of why it won’t work with XML documents, such as an XML mentioned in Amol Sawant’s comment. XML documents has to contain the header, such as
otherwise they are a plain string.
At all, your tutorial is handling this case, the link’s content as a string – it was very helpful to know this part of the xml parsing too – thank you very much for the tutorial:)
January 26th, 2012 - 12:52
Hello,
I really enjoyed your tutorial on xml and listviews. I was hoping to recreate the program myself however when I do so, I get No Data each time. I have attempted blanking out the lines you recommended in the comma (6-12 I think it was). Do you have any other suggestions as to why it might not be working?
Thanks!
Craig
January 30th, 2012 - 17:51
Hi I found your tutorial very useful! I do have a question however, how could you change the text color dynamically. For example if the score is less than 2000, change the text color to red.
This would help soo much.
thanks.
January 31st, 2012 - 17:38
cooooooolllllll
February 7th, 2012 - 00:17
I’m trying to use most of this code for a test app, but I’m trying to utilize and xml file that I’ve already added to R.raw instead of pulling it in from an http. I’m assuming I have to replace the getxml order with an InputStream command ?
Thanks for the tutorial.
February 8th, 2012 - 02:46
hi, thanks u very much!
February 8th, 2012 - 04:45
RE: Amol Sawant
Hi Amol, I had difficulties when testing on localhost too! It would simply crash each time I tried to use “http://localhost/” or “http://127.0.0.1″, I then tried the local IP of my machine and the issue was resolved!
So just use your local IP, eg: “http://192.168.x.x”. Let me know if it fixes the issue
Thanks
Jonny
February 11th, 2012 - 10:59
I’d like to ask how instead Toast.makeText call web browser whit url from xml? thx
February 12th, 2012 - 15:17
If somone can help me.
I have problem and ill explain on this example here:
i parsed all childs score–> 6958
and i want to have total sum of the score like…score 1 + score 2 = total score on the end of list. is this possible?
February 13th, 2012 - 00:31
Use 10.0.2.2 instead of localhost
http://10.0.2.2/amol/demo.xml
February 13th, 2012 - 05:58
Hey there. I was wondering how you set up your project? I downloaded your code and so forth and tried to open it up in Eclipse but the code doesn’t seem to pop up anywhere. But I will look through all the files and try to see how you set everything up. I am trying to set up my project in a kind of MVC sort of way.
February 13th, 2012 - 07:08
Ok. I think I figured out a way to get this thing to be more MVC based. I created a Utils folder and put all of XML functions and other utilities in there. I will leave the ListActivity inside the Web Interface folder as a kind of psuedo controller. I guess the model that we will use will be whatever we resolve the XML to, which will probably be an array of some sort I am guessing. What are your thoughts on making this into an MVC based project?
February 14th, 2012 - 07:54
Thanks Zohar!
I wasn’t aware that I could use 10.0.2.2 as localhost.
Amos, Zohar’s solution is better than what I offered, and means you won’t need to change the IP address in your code each time you switch your location.
Any chance someone could help me with my problem? I want to be able to change text color based on the score. if > 2000 text should be green if < it should be red. Any ideas?
Thanks
February 22nd, 2012 - 08:06
Jonny try with
if (XMLfunctions.getValue(e, “score”) >= “200″)
{
set color here
}
else
{
other color
}
Well i dont know for sure, but its idea