Check our Android Apps

GooglePlay.png

 

 

Android XML Parsing Tutorial

 

This android XML parsing tutorials show how to implement XML parsing in android application and how to read data from XML file by using a XML Parser.

   Project Description

  • XML stands for Extensible Markup Language which is commonly used for transporting and storing data.
  • Android XML parsing is used to retrieve data from a XML file by using XML parser with DOM(Document Object Model).
  • DOM is a cross platform for representing and interacting data in HTML and XML.
  • XML DOM parser is used to read data from XML file.

 

STEP BY STEP

1.Create an Android Project

Refer:-How to create an Android Project

2.In this android xml parsing tutorial we are going to create 3 class files such as

  • XMLParser.java
  • AndroidXMLParsingActivity.java
  • SingleItemActivity.java

3.Lets consider XMLParser first

In the XMLParser.java following operations are handling

  • By using HTTP Request getting the XML content.
  • Parsing the XML content and retrieve DOM element in the XML.
  • Retrieve each element child element value by using node name of element.

The bellow code shows XMLParser.java

package com.androidituts.xmlparsing;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class XMLParser {

// constructor
public XMLParser() {

}

//By using HTTP Request getting the XML content.

public String getXmlFromUrl(String url)

{
String xml = null;

try

{
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
//Parsing the XML content and retrieve DOM element in the XML.


public Document getDomElement(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) {
Log.e(“Error: “, e.getMessage());
return null;
} catch (SAXException e) {
Log.e(“Error: “, e.getMessage());
return null;
} catch (IOException e) {
Log.e(“Error: “, e.getMessage());
return null;
}

return doc;
}

/** Getting node value
* @param elem element
*/
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return “”;
}

//Retrieve each element child element value by using node name of element.
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}

 

4.Next we are going to leran about MainActivty class file named AndroidXMLParsingActivity.java

package com.androidituts.xmlparsing;

import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class AndroidXMLParsingActivity extends ListActivity {

// All static variables
static final String URL = “http://www.androidituts.com/source/tutorials.xml”;
// XML node keys
static final String KEY_ITEM = “item”; // parent node
static final String KEY_ID = “id”;
static final String KEY_NAME = “name”;
static final String KEY_CATEGORY = “category”;
static final String KEY_PUB = “published”;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element

NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_CATEGORY, “Category:-” + parser.getValue(e, KEY_CATEGORY));
map.put(KEY_PUB, parser.getValue(e, KEY_PUB));

// adding HashList to ArrayList
menuItems.add(map);
}

// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_NAME, KEY_CATEGORY, KEY_PUB }, new int[]
{
R.id.name, R.id.category, R.id.published });

setListAdapter(adapter);

// selecting single ListView item
ListView lv = getListView();

lv.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.category)).getText().toString();
String description = ((TextView) view.findViewById(R.id.published)).getText().toString();

// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_NAME, name);
in.putExtra(KEY_CATEGORY, cost);
in.putExtra(KEY_PUB, description);
startActivity(in);

}
});
}
}

Code Description

In the MainActivity we are getting the values from xml file by passing url.

In the above program uses the bellow code for getting values from xml file

static final String URL = http://www.androidituts.com/source/tutorials.xml;

The XML is shown bellow

<?xml version=”1.0″ encoding=”UTF-8″?>
<menu>
<item>
<id>1</id>
<name>Android Spinner Tutorial</name>
<category>Android Example</category>
<published>April 19 2013</published>
</item>
<item>
<id>2</id>
<name>Android UDP Client Server Example</name>
<category>Application</category>
<published>April 2 2013</published>
</item>
<item>
<id>3</id>
<name>Android UI Form Widgets</name>
<category>Android Components</category>
<published>November 11 2012</published>
</item>
<item>
<id>4</id>
<name>Android Manifest XML File</name>
<category>Android Beginners</category>
<published>November 7 2012 </published>
</item>
<item>
<id>5</id>
<name>Welcome to Android Development</name>
<category>Android Beginners</category>
<published>November 6 2012</published>
</item>
</menu>

5.This result shows by using the layout design .

Open the main.xml file from res/layout

In the main.xml we are providing the ListView

Code is shown bellow

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical”>
<!– Main ListView
Always give id value as list(@android:id/list)
–>
<ListView
android:id=”@android:id/list”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”/>

</LinearLayout>

6.Next we need to create an Android XML file named as list_item.xml

Copy and paste the following code

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:orientation=”vertical”>

<!– Name Label –>
<TextView
android:id=”@+id/name”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textColor=”#00FFFF”
android:textSize=”16sp”
android:textStyle=”bold”
android:paddingTop=”6dip”
android:paddingBottom=”2dip” />

<!– Category label –>
<TextView
android:id=”@+id/category”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textColor=”#FF9933″
android:paddingBottom=”2dip”>
</TextView>

<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:orientation=”horizontal”>
<!– Published Label –>
<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textColor=”#FFFF00″
android:gravity=”left”
android:textStyle=”bold”
android:text=”Published on: ” >
</TextView>

<TextView
android:id=”@+id/published”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:textColor=”#ffff”
android:textStyle=”bold”
android:gravity=”left”>
</TextView>
</LinearLayout>
</LinearLayout>

</LinearLayout>

 

7.Next we need another activity class.

This class is used when the user click on any item in the list,that particular item will be shown separately in another screen.

The bellow code shows SingleItemActivity.java

package com.androidituts.xmlparsing;

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

public class SingleItemActivity extends Activity {

// XML node keys
static final String KEY_NAME = “name”;
static final String KEY_CATEGORY = “category”;
static final String KEY_PUB = “published”;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_item);

// getting intent data
Intent in = getIntent();

// Get XML values from previous intent
String name = in.getStringExtra(KEY_NAME);
String cat = in.getStringExtra(KEY_CATEGORY);
String publish = in.getStringExtra(KEY_PUB);

// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCat = (TextView) findViewById(R.id.category_label);
TextView lblPub = (TextView) findViewById(R.id.published_label);

lblName.setText(name);
lblCat.setText(cat);
lblPub.setText(publish);
}
}

For displaying the single item,we need the design layout.

The bellow shows single_item.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<!– Name Label –>
<TextView android:id=”@+id/name_label”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textSize=”25dip”
android:textStyle=”bold”
android:paddingTop=”10dip”
android:paddingBottom=”10dip”
android:textColor=”#dc6800″/>
<!– Category Label –>
<TextView android:id=”@+id/category_label”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textColor=”#acacac”/>
<!– Published Label –>
<TextView android:id=”@+id/published_label”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:textStyle=”bold”/>
</LinearLayout>

 

8.Next we need to add the new activity in the AndroidManifest file and add Android Internet permission.

The code is shown bellow

<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”com.androidituts.xmlparsing”
android:versionCode=”1″
android:versionName=”1.0″ >

<uses-sdk android:minSdkVersion=”8″ />

<application
android:icon=”@drawable/icon”
android:label=”@string/app_name” >
<activity
android:label=”@string/app_name”
android:name=”.AndroidXMLParsingActivity” >
<intent-filter >
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>

<!– Single List Item View –>
<activity
android:label=”Single Item”
android:name=”.SingleItemActivity” >
</activity>
</application>

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

</manifest>

 

9.Next Run the android application

10.Output is shown bellow.

xml1_androidituts 

 

xml2_androidituts 

 

 

Check our Android Apps

GooglePlay.png