Can any body show how to get the data from xml document using SAX parsing for below XML example.
<root>
<parent>
<child1>xyz</child1>
<child2>abc</child2>
</parent>
</root>
for this how can we write the sax parsing code in android.
Thanks for helping...
There are lots of SAX Tutorial and answers available. Here is one of the good answers on StackOverflow that explains a clean chit how SAX Parser works!!!
public class JaappApplication extends Application {
public static final int FAIL = 0;
public static final int SUCCESS = 1;
//XML parsers
public static final int QUESTIONS = 0;
//PUTEXTRAS
public static final String SUBJECTID = "subjectid";
public static String subtypeid;
public static String subtypeoption;
}
public static ArrayList<QuestionsDto> getQuestionsDtos(String quesid)
{
ArrayList<QuestionsDto> arr = new ArrayList<QuestionsDto>();
String url1 = url + "getquestions.php?subjectid=" + quesid;
XMLParser xmlParser = new XMLParser(JaappApplication.QUESTIONS);
int x = xmlParser.parseXml(url1, JaappApplication.QUESTIONS);
arr = xmlParser.getQuestions();
return arr;
}
package com.jaapp.xmlparsing;
import java.io.InputStream;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import com.jaapp.application.JaappApplication;
import com.jaapp.dto.QuestionsDto;
import android.util.Log;
public class XMLParser {
protected static final String TAG = XMLParser.class.getCanonicalName();
private static QuestionsReader questionHandler;
public XMLParser(int initHandler) {
if (initHandler == JaappApplication.QUESTIONS) {
questionHandler = new QuestionsReader();
}
}
public int parseXml(String parseString, int type) {
try {
/* Create a URL we want to load some xml-data from. */
URI lUri = new URI(parseString);
// Prepares the request.
HttpClient lHttpClient = new DefaultHttpClient();
HttpGet lHttpGet = new HttpGet();
lHttpGet.setURI(lUri);
// Sends the request and read the response
HttpResponse lHttpResponse = lHttpClient.execute(lHttpGet);
InputStream lInputStream = lHttpResponse.getEntity().getContent();
int status = lHttpResponse.getStatusLine().getStatusCode();
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
if(type == JaappApplication.QUESTIONS) {
xr.setContentHandler(questionHandler);
}
/* Create a new ContentHandler and apply it to the XML-Reader */
/* Parse the xml-data from our URL. */
if (!((status >= 200) && (status < 300))) {
}
else
{
InputSource is = new InputSource(lInputStream);
is.setEncoding("ISO-8859-1");
xr.parse(is);
}
/* Parsing has finished. */
return JaappApplication.SUCCESS;
}
catch(UnknownHostException e)
{
Log.e(TAG, e.toString());
return JaappApplication.FAIL;
}
catch (Exception e) {
/* Display any Error to the GUI:. */
Log.e(TAG, e.toString());
return JaappApplication.FAIL;
}
}
public int parseXml(InputStream is, int type) {
try {
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
if(type == JaappApplication.QUESTIONS) {
xr.setContentHandler(questionHandler);
// } else if(type == NRTApplication.BOTTOMAD) {
// xr.setContentHandler(myBottomAdHandler);
}
/* Create a new ContentHandler and apply it to the XML-Reader */
/* Parse the xml-data from our URL. */
InputSource is1 = new InputSource(is);
is1.setEncoding("ISO-8859-1");
xr.parse(is1);
/* Parsing has finished. */
return JaappApplication.SUCCESS;
}
catch(UnknownHostException e)
{
Log.e(TAG, e.toString());
return JaappApplication.FAIL;
}
catch (Exception e) {
/* Display any Error to the GUI:. */
Log.e(TAG, "Exception XML parser: " + e.toString());
return JaappApplication.FAIL;
}
}
public ArrayList<QuestionsDto> getQuestions() {
return questionHandler.getQuestions();
}
}
package com.jaapp.xmlparsing;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
import com.jaapp.dto.QuestionsDto;
public class QuestionsReader extends DefaultHandler {
private static final String TAG = QuestionsReader.class.getCanonicalName();
private String tempVal;
private ArrayList<QuestionsDto> completeQuestionsList;
private QuestionsDto tempQues;
public QuestionsReader() {
completeQuestionsList = new ArrayList<QuestionsDto>();
}
#Override
public void startDocument() throws SAXException {
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equalsIgnoreCase("question")) {
tempQues = new QuestionsDto();
}
tempVal = "";
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal += new String(ch, start, length);
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (localName.equalsIgnoreCase("question")) {
completeQuestionsList.add(tempQues);
} else if(localName.equalsIgnoreCase("id")) {
tempQues.setQid(tempVal);
} else if(localName.equalsIgnoreCase("level")) {
tempQues.setQlevel(Integer.parseInt(tempVal));
} else if(localName.equalsIgnoreCase("description")) {
tempQues.setQquestion(tempVal);
}
}
public ArrayList<QuestionsDto> getQuestions() {
return completeQuestionsList;
}
}
Related
This is my xml content on a url over the internet:
<skus>
<item>
<id>r_1</id>
<size>10</size>
</item>
<item>
<id>c_1</id>
<size>10</size>
</item>
<item>
<id>d_1</id>
<size>10</size>
</item>
<item>
<id>e_1</id>
<size>10</size>
</item>
<item>
<id>f_1</id>
<size>10</size>
</item>
</skus>
This is SAXXMLParser Class:
public class SAXXMLParser {
public static List<XMLSetAdd> parse(InputStream is) {
List<XMLSetAdd> setAdds = null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHANDLER saxHandler = new SAXXMLHANDLER();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// getting the list`
setAdds = saxHandler.getIds();
} catch (Exception ex) {
Log.d("XML", "SAXXMLParser: parse() failed");
ex.printStackTrace();
}
// return The list
return setAdds;
}
}
This is my XMLSetAdd Class:
public class XMLSetAdd {
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getSize(){
return Size;
}
public void setSize(String Size){
this.Size = Size;
}
private String Id;
private String Size;
}
And This is my SAXXMLHANDLER:
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
setAdds = new ArrayList<XMLSetAdd>();
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
tempVal = "";
if (qName.equals("skus")){
}else if (qName.equals("item")){
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("item")) {
setAdds.add(setAdd);
} else if (qName.equals("id")) {
setAdd.setId(tempVal);
} else if (qName.equals("size")){
setAdd.setSize(tempVal);
}
}
}
And finally in terms of using it:
I have an async task with the purpose of reading xml content and filling it within a list. the result I get when I run this code is "ONE ROW" which is r_1. whereas it should return 5 results. ( I Also don't receive the size value)
I can't figure out which part of my code is wrong!
This is how you can do it
package com.teste;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
public class SAXXMLParser {
public static List<XMLSetAdd> parse(InputStream is) {
List<XMLSetAdd> setAdds = null;
try {
// create a XMLReader from SAXParser
XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser()
.getXMLReader();
// create a SAXXMLHandler
SAXXMLHANDLER saxHandler = new SAXXMLHANDLER();
// store handler in XMLReader
xmlReader.setContentHandler(saxHandler);
// the process starts
xmlReader.parse(new InputSource(is));
// getting the list`
setAdds = saxHandler.getIds();
System.out.println(setAdds.size());
for(int i=0;i<setAdds.size();i++)
{
System.out.println(setAdds.get(i).getId());
System.out.println(setAdds.get(i).getSize());
}
} catch (Exception ex) {
System.out.println("XML SAXXMLParser: parse() failed");
ex.printStackTrace();
}
// return The list
return setAdds;
}
public static void main(String[] args) throws FileNotFoundException {
SAXXMLParser parser = new SAXXMLParser();
InputStream inputStream = new FileInputStream(
"D:\\StackOverFlow\\JAXBTest\\src\\skus.xml");
parser.parse(inputStream);
System.out.println("parsed");
}
}
And
package com.teste;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXXMLHANDLER extends DefaultHandler {
private List<XMLSetAdd> setAdds;
private String tempVal;
// to maintain context
private XMLSetAdd setAdd;
public SAXXMLHANDLER() {
setAdds = new ArrayList<XMLSetAdd>();
}
public List<XMLSetAdd> getIds() {
return setAdds;
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
tempVal = "";
if (qName.equals("skus")){
}else if (qName.equals("item")){
if(setAdd!=null){
setAdds.add(setAdd);
}
setAdd = new XMLSetAdd();
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equals("id")) {
setAdd.setId(tempVal);
} else if (qName.equals("size")){
setAdd.setSize(tempVal);
}
}
}
There is no change in another class.. I have done it in Java remove main method and run it will work
I'm following a guid in Head First Android Development, and I can't seem to get this part right. The code is supposed to get a image with title and description from a Nasa RSS feed, but it does not retrieve the image. Any help would be awesome :)
package com.olshausen.nasadailyimage;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.os.Bundle;
import android.widget.ImageView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.widget.TextView;
public class DailyImage extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_daily_image);
IotdHandler handler = new IotdHandler ();
handler.processFeed();
resetDisplay (handler.getTitle(), handler.getDate(), handler.getImage(), handler.getDescription());
}
public class IotdHandler extends DefaultHandler {
private String url = "http://www.nasa.gov/rss/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
public void processFeed() {
try {
SAXParserFactory factory =
SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
InputStream inputStream = new URL(url).openStream();
reader.parse(new InputSource(inputStream));
} catch (Exception e) { }
}
private Bitmap getBitmap(String url) {
try {
HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bilde = BitmapFactory.decodeStream(input);
input.close();
return bilde;
} catch (IOException ioe) { return null; }
}
public void startElement(String url, String localName, String qName, Attributes attributes) throws SAXException {
if (localName.endsWith(".jpg")) { inUrl = true; }
else { inUrl = false; }
if (localName.startsWith("item")) { inItem = true; }
else if (inItem) {
if (localName.equals("title")) { inTitle = true; }
else { inTitle = false; }
if (localName.equals("description")) { inDescription = true; }
else { inDescription = false; }
if (localName.equals("pubDate")) { inDate = true; }
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) { String chars = new String(ch).substring(start, start + length);
if (inUrl && url == null) { image = getBitmap(chars); }
if (inTitle && title == null) { title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
private void resetDisplay (String title, String date, Bitmap image, StringBuffer description) {
TextView titleView = (TextView) findViewById (R.id.image_title);
titleView.setText(title);
TextView dateView = (TextView) findViewById(R.id.image_date);
dateView.setText(date);
ImageView imageView = (ImageView) findViewById (R.id.image_display);
imageView.setImageBitmap(image);
TextView descriptionView = (TextView) findViewById (R.id.image_description);
descriptionView.setText(description);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_daily_image, menu);
return true;
}
}
I must honestly say that I copied most of this code without checking it, the parser was "ready bake code", so its not really what is supposed to be tought in this chapter :)
Try using a framework instead - even the simplistic built-in framework is better than that horrible kludge you found.
This example uses the RootElement / Element and associated listeners from the android.sax package.
class NasaParser {
private String mTitle;
private String mDescription;
private String mDate;
private String mImageUrl;
public void parse(InputStream is) throws IOException, SAXException {
RootElement rss = new RootElement("rss");
Element channel = rss.requireChild("channel");
Element item = channel.requireChild("item");
item.setElementListener(new ElementListener() {
public void end() {
onItem(mTitle, mDescription, mDate, mImageUrl);
}
public void start(Attributes attributes) {
mTitle = mDescription = mDate = mImageUrl = null;
}
});
item.getChild("title").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
mTitle = body;
}
});
item.getChild("description").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
mDescription = body;
}
});
item.getChild("pubDate").setEndTextElementListener(new EndTextElementListener() {
public void end(String body) {
mDate = body;
}
});
item.getChild("enclosure").setStartElementListener(new StartElementListener() {
public void start(Attributes attributes) {
mImageUrl = attributes.getValue("", "url");
}
});
Xml.parse(is, Encoding.UTF_8, rss.getContentHandler());
}
public void onItem(String title, String description, String date, String imageUrl) {
// This is where you handle the item in the RSS channel, etc. etc.
// (Left as an exercise for the reader)
System.out.println("title=" + title);
System.out.println("description=" + description);
System.out.println("date=" + date);
// This needs to be downloaded for instance
System.out.println("imageUrl=" + imageUrl);
}
}
This Ready bake code has two problems
The Network connection is made from the main UI thread.()
How to fix android.os.NetworkOnMainThreadException?
The Image is not retrieved from the XML properly in the example
so just add one member variable for the imageUrl and access it by first reading enclosure and then url.
So the final code will be look like..
package com.Achiileus.nasadailyimageamazing;//your package name
import org.xml.sax.helpers.DefaultHandler;
import android.annotation.SuppressLint;
import android.graphics.*;
import android.os.StrictMode;
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.HttpURLConnection;
import java.io.IOException;
#SuppressLint("NewApi")
public class IotdHandler extends DefaultHandler {
private String url = "http://www.nasa.gov/rss/image_of_the_day.rss";
private boolean inUrl = false;
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private Bitmap image = null;
private String imageUrl=null;
private String title = null;
private StringBuffer description = new StringBuffer();
private String date = null;
public void processFeed() {
try {
//This part is added to allow the network connection on a main GUI thread...
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(this);
URL urlObj = new URL(url);
InputStream inputStream = urlObj.openConnection().getInputStream();
reader.parse(new InputSource(inputStream));
}
catch (Exception e)
{
e.printStackTrace();
System.out.println(new String("Got Exception General"));
}
}
private Bitmap getBitmap(String url) {
try {
System.out.println(url);
HttpURLConnection connection =
(HttpURLConnection)new URL(url).openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
input.close();
return bitmap;
}
catch (IOException ioe)
{
System.out.println(new String("IOException in reading Image"));
return null;
}
catch (Exception ioe)
{
System.out.println(new String("IOException GENERAL"));
return null;
}
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException
{
if (localName.equals("enclosure"))
{
System.out.println(new String("characters Image"));
imageUrl = attributes.getValue("","url");
System.out.println(imageUrl);
inUrl = true;
}
else { inUrl = false; }
if (localName.startsWith("item")) { inItem = true; }
else if (inItem) {
if (localName.equals("title")) { inTitle = true; }
else { inTitle = false; }
if (localName.equals("description")) { inDescription = true; }
else { inDescription = false; }
if (localName.equals("pubDate")) { inDate = true; }
else { inDate = false; }
}
}
public void characters(char ch[], int start, int length) {
System.out.println(new String("characters"));
String chars = new String(ch).substring(start, start + length);
System.out.println(chars);
if (inUrl && image == null)
{
System.out.println(new String("IMAGE"));
System.out.println(imageUrl);
image = getBitmap(imageUrl);
}
if (inTitle && title == null) {
System.out.println(new String("TITLE"));
title = chars; }
if (inDescription) { description.append(chars); }
if (inDate && date == null) { date = chars; }
}
public Bitmap getImage() { return image; }
public String getTitle() { return title; }
public StringBuffer getDescription() { return description; }
public String getDate() { return date; }
}
Seems like your main issue is in your parse() method. You will never get the image by using this condition: if (localName.endsWith(".jpg")), that will never be true. Instead, you want to make sure you're inside an enclosure tag, and then you want to read the attributes so you get the url one. So first update your clause to be if (localName.endsWith("url")) { ... }. Then to get the actual URL attribute, you can check how to do that from this link.
package com.headfirstlabs.ch03.nasa.iotd;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.content.Context;
import android.util.Log;
public class IotdHandler extends DefaultHandler {
private static final String TAG = IotdHandler.class.getSimpleName();
private boolean inTitle = false;
private boolean inDescription = false;
private boolean inItem = false;
private boolean inDate = false;
private String url = null;
private StringBuffer title = new StringBuffer();
private StringBuffer description = new StringBuffer();
private String date = null;
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (localName.equals("enclosure")) {
url = attributes.getValue("url");
}
if (localName.startsWith("item")) {
inItem = true;
} else {
if (inItem) {
if (localName.equals("title")) {
inTitle = true;
} else {
inTitle = false;
}
if (localName.equals("description")) {
inDescription = true;
} else {
inDescription = false;
}
if (localName.equals("pubDate")) {
inDate = true;
} else {
inDate = false;
}
}
}
}
public void characters(char ch[], int start, int length) {
String chars = (new String(ch).substring(start, start + length));
if (inTitle) {
title.append(chars);
}
if (inDescription) {
description.append(chars);
}
if (inDate && date == null) {
//Example: Tue, 21 Dec 2010 00:00:00 EST
String rawDate = chars;
try {
SimpleDateFormat parseFormat = new SimpleDateFormat("EEE, dd MMM yyyy
HH:mm:ss");
Date sourceDate = parseFormat.parse(rawDate);
SimpleDateFormat outputFormat = new SimpleDateFormat("EEE, dd MMM yyyy");
date = outputFormat.format(sourceDate);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void processFeed(Context context, URL url) {
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
Log.e("", e.toString());
} catch (SAXException e) {
Log.e("", e.toString());
} catch (ParserConfigurationException e) {
Log.e("", e.toString());
}
}
public String getUrl() {
return url;
}
public String getTitle() {
return title.toString();
}
public String getDescription() {
return description.toString();
}
public String getDate() {
return date;
}
}
I am new in android. I want to create a application to read the XML file from an URL and show the image in a grid view using ImageUrl of image.
Thanks for the answer but I am able to read xml file from url but I need if in xml imageUrl is there so show in grid view.
This is my xml file
<?xml version="1.0" encoding="UTF-8"?>
<channels>
<channel>
<name>ndtv</name>
<logo>http://a3.twimg.com/profile_images/670625317/aam-logo-v3-twitter.png</logo>
<description>this is a news Channel</description>
<rssfeed>ndtv.com</rssfeed>
</channel>
<channel>
<name>star news</name>
<logo>http://a3.twimg.com/profile_images/740897825/AndroidCast-350_normal.png</logo>
<description>this is a news Channel</description>
<rssfeed>starnews.com</rssfeed>
</channel>
</channels>
Check the following URl to kow about XML parsers
http://www.totheriver.com/learn/xml/xmltutorial.html#6.2
First get the data from url. store in in file. use the folowing code to parse the XML using SAXParser
SAX Parser to parse an XML
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class SAXParserExample extends DefaultHandler{
List myEmpls;
private String tempVal;
//to maintain context
private Employee tempEmp;
public SAXParserExample(){
myEmpls = new ArrayList();
}
public void runExample() {
parseDocument();
printData();
}
private void parseDocument() {
//get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
//get a new instance of parser
SAXParser sp = spf.newSAXParser();
//parse the file and also register this class for call backs
sp.parse("employees.xml", this);
}catch(SAXException se) {
se.printStackTrace();
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch (IOException ie) {
ie.printStackTrace();
}
}
/**
* Iterate through the list and print
* the contents
*/
private void printData(){
System.out.println("No of Employees '" + myEmpls.size() + "'.");
Iterator it = myEmpls.iterator();
while(it.hasNext()) {
System.out.println(it.next().toString());
}
}
//Event Handlers
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
//reset
tempVal = "";
if(qName.equalsIgnoreCase("Employee")) {
//create a new instance of employee
tempEmp = new Employee();
tempEmp.setType(attributes.getValue("type"));
}
}
public void characters(char[] ch, int start, int length) throws SAXException {
tempVal = new String(ch,start,length);
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if(qName.equalsIgnoreCase("Employee")) {
//add it to the list
myEmpls.add(tempEmp);
}else if (qName.equalsIgnoreCase("Name")) {
tempEmp.setName(tempVal);
}else if (qName.equalsIgnoreCase("Id")) {
tempEmp.setId(Integer.parseInt(tempVal));
}else if (qName.equalsIgnoreCase("Age")) {
tempEmp.setAge(Integer.parseInt(tempVal));
}
}
public static void main(String[] args){
SAXParserExample spe = new SAXParserExample();
spe.runExample();
}
}
Working with XML on Android
Grid View example
I've got a custom contentHandler (called XMLHandler), I've been to a lot of sites via Google and StackOverflow that detail how to set that up.
What I do not understand is how to USE it.
Xml.parse(...,...) returns nothing, because it is a void method.
How do I access my parsed XML data?
I realize this question is probably trivial, but I've been searching for (literally) hours and have found no solution.
Please help.
String result = fetchData(doesntmatter);
Xml.parse(result, new XMLHandler());
Here is one example i hope it will be usefull to understand "SAXParser"
package test.example;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
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 org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class XMLParsingDemo extends Activity {
private final String MY_DEBUG_TAG = "WeatherForcaster";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
/* Create a new TextView to display the parsingresult later. */
TextView tv = new TextView(this);
try {
/* Create a URL we want to load some xml-data from. */
DefaultHttpClient hc = new DefaultHttpClient();
ResponseHandler <String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.anddev.org/images/tut/basic/parsingxml/example.xml");
String response=hc.execute(postMethod,res);
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
ExampleHandler myExampleHandler = new ExampleHandler();
xr.setContentHandler(myExampleHandler);
/* Parse the xml-data from our URL. */
InputSource inputSource = new InputSource();
inputSource.setEncoding("UTF-8");
inputSource.setCharacterStream(new StringReader(response));
/* Parse the xml-data from our URL. */
xr.parse(inputSource);
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
ParsedExampleDataSet parsedExampleDataSet = myExampleHandler.getParsedData();
/* Set the result to be displayed in our GUI. */
tv.setText(response + "\n\n\n***************************************" + parsedExampleDataSet.toString());
} catch (Exception e) {
/* Display any Error to the GUI. */
tv.setText("Error: " + e.getMessage());
Log.e(MY_DEBUG_TAG, "WeatherQueryError", e);
}
/* Display the TextView. */
this.setContentView(tv);
}
public class ExampleHandler extends DefaultHandler {
// ===========================================================
// Fields
// ===========================================================
private boolean in_outertag = false;
private boolean in_innertag = false;
private boolean in_mytag = false;
private ParsedExampleDataSet myParsedExampleDataSet = new ParsedExampleDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public ParsedExampleDataSet getParsedData() {
return this.myParsedExampleDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.myParsedExampleDataSet = new ParsedExampleDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException {
super.startElement(uri, localName, qName, atts);
if (localName.equals("outertag")) {
this.in_outertag = true;
}
else if (localName.equals("innertag")) {
String attrValue = atts.getValue("sampleattribute");
myParsedExampleDataSet.setExtractedString(attrValue);
this.in_innertag = true;
}
else if (localName.equals("mytag")) {
this.in_mytag = true;
}
else if (localName.equals("tagwithnumber")) {
// Extract an Attribute
String attrValue = atts.getValue("thenumber");
int i = Integer.parseInt(attrValue);
myParsedExampleDataSet.setExtractedInt(i);
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("outertag")) {
this.in_outertag = false;
}else if (localName.equals("innertag")) {
this.in_innertag = false;
}else if (localName.equals("mytag")) {
this.in_mytag = false;
}else if (localName.equals("tagwithnumber")) {
// Nothing to do here
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_mytag){
myParsedExampleDataSet.setExtractedString(new String(ch));
}
}
}
public class ParsedExampleDataSet {
private String extractedString = null;
private int extractedInt = 0;
public String getExtractedString() {
return extractedString;
}
public void setExtractedString(String extractedString) {
this.extractedString = extractedString;
}
public int getExtractedInt() {
return extractedInt;
}
public void setExtractedInt(int extractedInt) {
this.extractedInt = extractedInt;
}
public String toString(){
return "\n\n\nExtractedString = " + this.extractedString
+ "\n\n\nExtractedInt = " + this.extractedInt;
}
}
}
You have to access your XML data into handler which you have define by XMLHandler()
you have to override
public void startElement(String uri, String localName, String qName, org.xml.sax.Attributes atts) throws SAXException {
}
#Override
public void endElement(String namespaceURI, String localName, String qName) {
}
and
#Override
public void characters(char ch[], int start, int length) {
}
GridActivity.java
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class GridActivity extends Activity
{
ArrayList<String> imageurl=new ArrayList<String>();
String albumId= ConstantData.album_id;
String userId = ConstantData.user_id;
int pageNo =1;
int limit = 20;
ArrayList<Object> result;
XmlParser parser;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photos_activity);
//Add required urls
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.5.10/ijoomer_development/index.php?option=com_ijoomer&plg_name=jomsocial&pview=album&ptask=photo_paging&userid="+ ConstantData.user_id +"&sessionid="+ ConstantData.session_id +"&tmpl=component&albumid="+ ConstantData.album_id +"&pageno=1&limit=20");
StringBuffer strBuffer = new StringBuffer("<data><userid>" + userId + "</userid><albumid>" + albumId + "</albumid><pageno>" + pageNo +"</pageno><limit>"+ limit +"</limit></data>");
StringEntity strEntity = new StringEntity(strBuffer.toString());
post.setEntity(strEntity);
HttpResponse response = client.execute(post);
InputStream in = response.getEntity().getContent();
String strResponse = convertStreamToString(in);
parser = new XmlParser(in, new AddAlbumDetailBean());
result = parser.parse("data", "photo");
//Log.i("aBean Value", ""+aBean);
//System.out.println(strResponse);
String startCode = "<code>";
String endCode = "</code>";
String starPhotoCount = "<photocount>";
String endPhotoCount ="</photocount>";
String starPhotos = "<photos>";
String endPhotos ="</photos>";
String startPhoto = "<photo>";
String endPhoto = "</photo>";
String startId = "<Id>";
String endId = "</Id>";
String starTitle = "<title>";
String endTitle ="</title>";
String startThumb ="<thumb>";
String endThumb = "</thumb>";
String startUrl = "<url>";
String endUrl = "</url>";
if (startCode.equalsIgnoreCase("<code>") && endCode.equalsIgnoreCase("</code>"))
{
int startC = strResponse.indexOf(startCode);
int endC = strResponse.indexOf(endCode);
Log.i("startCode", ""+startC);
Log.i("endCode", ""+endC);
String OldCode = strResponse.substring(startC, endC);
int startCodeindex = OldCode.indexOf(">");
String code = OldCode.substring(startCodeindex + 1).trim();
Log.i("Code", ""+code);
}
if (starPhotoCount.equalsIgnoreCase("<photocount>") && endPhotoCount.equalsIgnoreCase("</photocount>"))
{
int startPC = strResponse.indexOf(starPhotoCount);
int endPC = strResponse.indexOf(endPhotoCount);
Log.i("starPhotoCount", ""+startPC);
Log.i("endPhotoCount", ""+endPC);
String OldPC = strResponse.substring(startPC, endPC);
int startPCindex = OldPC.indexOf(">");
String photocount = OldPC.substring(startPCindex + 1).trim();
Log.i("PhotoCount", ""+photocount);
}
if (starPhotos.equalsIgnoreCase("<photos>") && endPhotos.equalsIgnoreCase("</photos>"))
{
int startPs = strResponse.indexOf(starPhotos);
int endPs = strResponse.indexOf(endPhotos);
Log.i("starPhotos", ""+startPs);
Log.i("endPhotos", ""+endPs);
String OldPhotos = strResponse.substring(startPs, endPs);
int startPhotosindex = OldPhotos.indexOf(">");
String photos = OldPhotos.substring(startPhotosindex + 1).trim();
Log.i("Photos", ""+photos);
}
if (startPhoto.equalsIgnoreCase("<photo>") && endPhoto.equalsIgnoreCase("</photo>"))
{
int startP = strResponse.indexOf(startPhoto);
int endP = strResponse.indexOf(endPhoto);
Log.i("startPhoto", ""+startP);
Log.i("endPhoto", ""+endP);
String OldThumb = strResponse.substring(startP, endP);
int startUrlindex = OldThumb.indexOf(">");
String photo = OldThumb.substring(startUrlindex + 1).trim();
Log.i("Photo", ""+photo);
}
/*if (startId.equalsIgnoreCase("<id>") && endId.equalsIgnoreCase("</id>"))
{
int startI = strResponse.indexOf(startId);
int endI = strResponse.indexOf(endId);
Log.i("startId", ""+startI);
Log.i("endId", ""+endI);
String OldId = strResponse.substring(startI, endI);
int startIdindex = OldId.indexOf(">");
String id = OldId.substring(startIdindex + 1).trim();
Log.i("ID", ""+id);
}*/
if (starTitle.equalsIgnoreCase("<title>") && endTitle.equalsIgnoreCase("</title>"))
{
int startT = strResponse.indexOf(starTitle);
int endT = strResponse.indexOf(endTitle);
Log.i("startTitle", ""+startT);
Log.i("endTitle", ""+endT);
String OldTitle = strResponse.substring(startT, endT);
int startTitleindex = OldTitle.indexOf(">");
String title = OldTitle.substring(startTitleindex + 1).trim();
Log.i("Title", ""+title);
}
if (startThumb.equalsIgnoreCase("<thumb>") && endThumb.equalsIgnoreCase("</thumb>"))
{
int startTh = strResponse.indexOf(startThumb);
int endTh = strResponse.indexOf(endThumb);
Log.i("startThumb", ""+startTh);
Log.i("endThumb", ""+endTh);
String OldThumb = strResponse.substring(startTh, endTh);
int startthumbindex = OldThumb.indexOf(">");
String thumb = OldThumb.substring(startthumbindex + 1).trim();
Log.d("Thumb Url", thumb);
imageurl.add(thumb);
Log.i("Thu0mb", ""+thumb);
}
if (startUrl.equalsIgnoreCase("<url>") && endId.equalsIgnoreCase("</url>"))
{
int startU = strResponse.indexOf(startUrl);
int endU = strResponse.indexOf(endUrl);
Log.i("startUrl", ""+startU);
Log.i("endUrl", ""+endU);
String OldUrl = strResponse.substring(startU, endU);
int startUrlindex = OldUrl.indexOf(">");
String strUrl = OldUrl.substring(startUrlindex + 1).trim();
Log.i("Url", ""+strUrl);
}
}
catch (Exception e) {
e.printStackTrace();
}
/*imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");
imageurl.add("http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png");*/
GridView gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView parent,
View v, int position, long id)
{
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected",
Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c)
{
context = c;
}
public int getCount() {
Log.i("SiZE of ImageUrl", ""+imageurl.size());
return imageurl.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
/*AddAlbumDetailBean aBean = (AddAlbumDetailBean)result.get(position);
imageurl.add(aBean.thumb);*/
String strURL=imageurl.get(position);
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
URL url;
try {
url = new URL(strURL);
URLConnection conn = url.openConnection();
in=conn.getInputStream();
Bitmap bitmap1= BitmapFactory.decodeStream(in);
imageView.setImageBitmap(bitmap1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//imageView.setImageResource(imagen]);
return imageView;
}
}
public String convertStreamToString(InputStream in)
throws IOException {
if (in != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
// in.close();
}
return writer.toString();
} else {
return "";
}
}
}
XMLParser.java
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Vector;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XmlParser extends DefaultHandler{
public String RootElement;
public String RecordElement;
public InputStream in;
public Object mainObj;
public Object newObj;
public boolean inProcess;
public String xmlURL;
public ArrayList<Object> Records = null;
private final String TAG = "XmlParser";
StringBuffer buffer = new StringBuffer();
String elementName;
String elementValue;
public XmlParser(InputStream is,Object tempObj)
{
in = is;
mainObj = tempObj;
Log.i("Object value", ""+mainObj);
inProcess = false;
}
public XmlParser(String strURL,Object tempObj)
{
xmlURL = strURL;
mainObj = tempObj;
inProcess = false;
}
public ArrayList<Object> ParseUrl(String rootElement ,String recordElement)
{
RootElement = rootElement;
Log.i("RootElement",RootElement);
RecordElement = recordElement;
Log.i("RecordElement", RecordElement);
try
{
URL sourceUrl = new URL(xmlURL);
Log.d("URl", xmlURL);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader reader = sp.getXMLReader();
reader.setContentHandler(this);
reader.parse(new InputSource(sourceUrl.openStream()));
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
return this.Records;
}
public ArrayList<Object> parse(String rootElement, String recordElement)
{
RootElement = rootElement;
RecordElement = recordElement;
Log.i("Root Element", ""+RootElement);
Log.i("Record Element", ""+RecordElement);
try{
SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(in, this);
}catch(Exception e){
e.printStackTrace();
return null;
}
return this.Records;
}
#Override
public void startElement(String Uri, String localName,String qName,Attributes attributes) throws SAXException
{
Log.d("URl", xmlURL);
elementValue = "";
Log.i("IN STARTELEMENT", ""+elementValue);
if(localName.length() > 0)
{
Log.i("Local Name Length", ""+localName.length());
Log.i("LocalName", ""+localName);
if(localName.equalsIgnoreCase(RootElement))
{
Records = new ArrayList<Object>();
Log.i("Root element", ""+RootElement);
Log.i("Records", ""+Records);
}
else if(localName.equalsIgnoreCase(RecordElement))
{
newObj = ClassUtils.newObject(mainObj);
Log.i("Main Object", ""+mainObj);
Log.i("Record element", ""+RecordElement);
ClassUtils.objectMapping(newObj, localName, elementValue);
Log.i("Element Value", ""+elementValue);
inProcess = true;
}
}
}
#Override
public void characters(char[] ch,int start,int length) throws SAXException{
elementValue+= new String(ch,start,length).trim();
Log.i("CHARACTERS VALUE", ""+elementValue);
}
#Override
public void endElement(String Uri,String localName,String qName) throws SAXException
{
if(localName.equalsIgnoreCase(RecordElement)){
Records.add(newObj);
inProcess = false;
}
else if(inProcess){
ClassUtils.objectMapping(newObj, localName, elementValue);
}
}
}
AddAlbumDetailActivity.java
import android.util.Log;
public class AddAlbumDetailBean
{
public String data = null;
public String code = null;
public String photocount = null;
public String id = null;
public String title = null;
public String thumb = null;
public String url = null;
public AddAlbumDetailBean()
{
this("","","","","","","");
}
public AddAlbumDetailBean(String data,String code,String photocount,String id,String title,String thumb,String url)
{
this.data = data;
this.code = code;
this.photocount = photocount;
this.id = id;
this.title = title;
this.thumb = thumb;
this.url = url;
}
}
While using grid view it is not easy to Set the Image View. but you can do it by trick.
Take Button instead of the Image and set the Button Background for the Appropriate image.
After that u can able to set the Set the Button in grid view.
Thanks.