Android XML Parsing Using SAX Parser


I have below xml file.Now Get Data from xml file using SAX 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>Part of the English Sports range. The Cricket Wallpaper builds on the small pattern repeat of traditional papers.</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>Whatever your industry, if you’re a full time professional, your smartphone is your best friend.</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>



 SAXParser in Android

SAX stands for Simple API for XML.SAX was the first widely adopted API for XML in java.


A SAX parser can be instructed to stop midway through a document without losing the data already collected. This is one of the most commonly mentioned advantages of a SAX parser over a DOM parser, which generally creates an in-memory structure of the entire document. In this tip, you'll parse a list of recently updated weblogs, stopping when you've displayed all those within a particular time range.



It examines an XML file, character by character, and translates it into a series of events, such as startDocument() and endElement(). A ContentHandler object processes these events, taking appropriate action. An ErrorHandler object takes care of any warnings or errors that arise during the parsing. The main application (see Listing 1) assigns these objects to the XMLReader object:
The parse() method simply sends the events to the content object, which then deals with them.




Why and when to use SAX(Simple API for XML) over DOM (Document Object Model)?


1). The quantity of memory that a SAX parser must use in order to function is typically much smaller than that of a DOM parser. DOM parsers must have the entire Object tree in memory before any processing can begin, so the amount of memory used by a DOM parser depends entirely on the size of the input data.
2). Because of the event-driven nature of SAX, processing documents can often be faster than DOM-style parsers. Memory allocation takes time, so the larger memory footprint of the DOM is also a performance issue.
3). Due to the nature of DOM, streamed reading from disk is impossible. Processing XML documents larger than main memory is also impossible with DOM parsers but can be done with SAX parsers. However, DOM parsers may make use of disk space as memory to side step this limitation.



ItemXMLHandler.java 


package com.samir;


import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class ItemXMLHandler extends DefaultHandler {


Boolean currentElement = false;
String currentValue = "";
Bean item = null;
private ArrayList<Bean> itemsList = new ArrayList<Bean>();


public ArrayList<Bean> getItemsList() {
return itemsList;
}


// Called when tag starts
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {


currentElement = true;
currentValue = "";


if (localName.equals("item")) {
item = new Bean();
}


}


// Called when tag closing
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {


currentElement = false;


if (localName.equals("id")) {
item.setId(currentValue);
} else if (localName.equals("title")) {
item.setTitle(currentValue);
} else if (localName.equals("desc")) {
item.setDesc(currentValue);
} else if (localName.equals("pubDate")) {
item.setPubDate(currentValue);
} else if (localName.equals("link")) {
item.setLink(currentValue);
} else if (localName.equals("item")) {
itemsList.add(item);
}
}


// Called to get tag characters
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {


if (currentElement) {
currentValue = currentValue + new String(ch, start, length);
}
}
}


MainActivity.java

package com.samir;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

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.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private ProgressDialog pDialog;
private ItemXMLHandler myXMLHandler;
private String rssFeed = "https://www.dropbox.com/s/t4o5wo6gdcnhgj8/imagelistview.xml?dl=1";
    private TextView textview;
@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) {

try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();

myXMLHandler = new ItemXMLHandler();
xr.setContentHandler(myXMLHandler);

URL _url = new URL(params[0]);

xr.parse(new InputSource(_url.openStream()));

} catch (ParserConfigurationException pce) {
Log.e("SAX XML", "sax parse error", pce);
} catch (SAXException se) {
Log.e("SAX XML", "sax error", se);
} catch (IOException e) {
e.printStackTrace();
}
return null;

}

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

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

ArrayList<Bean> itemsList = myXMLHandler.getItemsList();

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 Souce From Here


3 comments:

  1. Thank you.....very useful tutorial....!!!

    ReplyDelete
  2. hey what an useful tutorial, I spend more than 2 days trying to get a tutorial like this one, and just this one worked !!..Thanks so much.!

    ReplyDelete
  3. thanks for this tutorial... but i have a problem... how can i display the images and texts???? it just display Done!!!

    ReplyDelete

Android Testing App