Android XML Parsing Using DOM Parser

I have below xml file.Now Get Data from xml file using DOM Parser.

<?xml version="1.0" encoding="utf-8"?>
<rss>
<item>

<id>1</id>
<title>Image 1</title>
<desc>Whether it's made with soy byproducts, milk, or clay, these natural wall color options are healthy for your home.</desc>
<pubDate>22/03/2012</pubDate>
<link>https://www.dropbox.com/s/jpqsvse4xx9qt96/image1.jpg?dl=1</link>
</item>

<item>
<id>2</id>
<title>Image 2</title>
<desc></desc>
<pubDate>23/03/2012</pubDate>
<link>https://www.dropbox.com/s/n29704f65zigty7/image2.jpeg?dl=1</link>
</item>

<item>
<id>3</id>
<title>Image 3</title>
<desc></desc>
<pubDate>27/03/2012</pubDate>
<link>https://www.dropbox.com/s/1l3qoojbi4drqsd/image3.jpeg?dl=1</link>
</item>

<item>
<id>4</id>
<title>Image 4</title>
<desc>Natural paints are generally more expensive than conventional paints and arenĂ¢€™t always widely available, but can be ordered online.</desc>
<pubDate>29/03/2012</pubDate>
<link>https://www.dropbox.com/s/f9n3u3d5okk9x2v/image4.jpg?dl=1</link>
</item>
</rss>

now above xml file have item tag is Nodelist.and child nodes are id,title,desc,pubdate,link.
NodeList nList = doc.getElementsByTagName("item");
you can get length of nodelist using getLength.and retrieve one by one child nodes.


for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
           Element eElement = (Element) nNode;
 }


now using  eElement you can getvalue of nodes
private static String getTagValue(String sTag, Element eElement) {
NodeList nList = eElement.getElementsByTagName(sTag).item(0) .getChildNodes(); if (eElement.getNodeType() == Node.ELEMENT_NODE) {
if (nList != null && nList.getLength() > 0) {
            return nList.item(0).getNodeValue();  
}
} return null; 
  }



DOMParser.java 


package com.samir;


import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class DOMParser {
Bean objItem;
List<Bean> listArray;


public List<Bean> getData(String url) {


try {
listArray = new ArrayList<Bean>();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
doc.getDocumentElement().normalize();


NodeList nList = doc.getElementsByTagName("item");
for (int temp = 0; temp < nList.getLength(); temp++) {


Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
objItem = new Bean();
objItem.setId(getTagValue("id", eElement));
objItem.setTitle(getTagValue("title", eElement));
objItem.setDesc(getTagValue("desc", eElement));
objItem.setPubDate(getTagValue("pubDate", eElement));
objItem.setLink(getTagValue("link", eElement));
listArray.add(objItem);
}
}
} catch (Exception e) {
e.printStackTrace();
}


return listArray;
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
if (eElement.getNodeType() == Node.ELEMENT_NODE) {
if (nList != null && nList.getLength() > 0) {
return nList.item(0).getNodeValue();
}
}
return null;
}
}

MainActivity.java

package com.samir;

import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private ProgressDialog pDialog;
private String rssFeed = "https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
private TextView textview;
private List<Bean> itemsList;

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

textview = (TextView) findViewById(R.id.textView1);
}

public void doParsing(View v) {

if (isNetworkAvailable()) {
textview.setText("Loading...Please wait...");
new AsyncData().execute(rssFeed);
} else {
showToast("No Network Connection!!!");
}
}

class AsyncData extends AsyncTask<String, Void, Void> {

@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setTitle("Loading....");
pDialog.setMessage("Please wait...");
pDialog.show();
super.onPreExecute();
}

@Override
protected Void doInBackground(String... params) {
itemsList = new DOMParser().getData(params[0]);
return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);

textview.setText("Done!!! See Your Logcat...");
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}

if (null != itemsList && itemsList.size() != 0) {
for (int index = 0; index < itemsList.size(); index++) {
Bean objBean = itemsList.get(index);

System.out.println(">>>>>>>>>>>>>>>" + index);
System.out.println("ID :: " + objBean.getId());
System.out.println("TITLE :: " + objBean.getTitle());
System.out.println("DESC :: " + objBean.getDesc());
System.out.println("PUBDATE :: " + objBean.getPubDate());
System.out.println("LINK :: " + objBean.getLink());
}
}
}
}

public void showToast(String msg) {
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
}

public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}

Bean.java


package com.samir;
public class Bean {
private String id;
private String title;
private String desc;
private String pubDate;
private String link;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}


DownLoad Full Project From Here...
      Download Full Source Code


2 comments:

  1. Pls can you help me
    http://stackoverflow.com/questions/13866480/android-dom-parser-search-activity

    ReplyDelete
  2. I have doubt at:
    objItem = new Bean();
    objItem.setId(getTagValue("id", eElement));
    objItem.setTitle(getTagValue("title", eElement));
    objItem.setDesc(getTagValue("desc", eElement));
    objItem.setPubDate(getTagValue("pubDate", eElement));
    objItem.setLink(getTagValue("link", eElement));
    //at this line
    listArray.add(objItem);

    as we see...we are adding objItem to List. But objItem object is called on setId(),setDesc()...etc whic dont return any value so How and what values are added in List ? Plz help me I am beginner in Android

    ReplyDelete

Android Testing App