I'm trying to parse xml from the code bellow:
XMLParser xmlParser = new XMLParser();
String xml = xmlParser.getXmlFromUrl(URL2);
Document doc = xmlParser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName("item");
Element e = (Element) nl.item(0);
that's working properly when URL2 = http://api.androidhive.info/pizza/?format=xml
But when im using my server: URL2 = http://udios.bugs3.com/test.xml it falls in the last line:
NodeList nl = doc.getElementsByTagName("item");
with the following exception:
NullPointerException
Unexpected token (position:TEXT #1:4 in java.io.StringReader#41391770)
The 2 xml files are identical, and i don't thing that the problem is in the server, maybe encoding problem?
I would appreciate if someone will help me
thanks
i think this link is used full...
check this Link
i have shown with only <name>...</name> tag, do the same with <id>...</id> , <cost>...</cost> and <description>...</description>
TextView name[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(URL2);
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+sitesList.getName().get(i));
}
MyXMLHandler.java
/* This file is used to handle the XML tags. So we need to extends with DefaultHandler.
we need to override startElement, endElement & characters method .
startElemnt method called when the tag starts.
endElemnt method called when the tag ends
characres method to get characters inside tag.
*/
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/** Called when tag starts ( ex:- <name>Android</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("menu"))
{
/** Start */
sitesList = new SitesList();
}
}
/** Called when tag closing ( ex:- <name>Android</name>
* -- </name> )*/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("name"))
sitesList.setName(currentValue);
}
/** Called to get tag characters ( ex:- <name>Android</name>
* -- to get Android Character ) */
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
SitesList.java
// Contains Getter & Setter Method
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList {
/** Variables */
private ArrayList<String> name = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getName() {
return name;
}
public void setName(String name) {
this.name.add(name);
}
}
found workaround:
took the xml - open with notepad - save as (ANSI)
Related
I'm using the sax xmlparser and I am unable to print results through toast. I get a null pointer exception. I found an example that uses textview array but I want to use toast. The original code from android people works fine, but if I apply the same code in my own project it fails everytime.
Main.java >
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
public class Main extends Activity {
String strGK = null;
String strHWW = null;
String strHak5 = null;
CheckBox GK;
CheckBox HWW;
CheckBox Hak5;
SitesList sitesList = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void getUrl(View v) {
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("http://websitethatcontains/feed");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Parsing Exception = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) { /** <- the prob. seems to be here */
Toast.makeText(getApplicationContext(), sitesList.getName().get(i), Toast.LENGTH_LONG).show();
}
}
}
try
public void getUrl(View v) {
MyXMLHandler myXMLHandler;
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL("http://websitethatcontains/feed");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Parsing Exception = " + e);
}
if (MyXMLHandler != null){
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getName().size(); i++) { /** <- the prob. seems to be here */
Toast.makeText(getApplicationContext(), sitesList.getName().get(i), Toast.LENGTH_LONG).show();
}
}
}
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;
}
}
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) {
}
I am trying to parse a URL in Android but it gives a null value except category. Can you help me fix it?
//my main.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
</LinearLayout>
//sitelist.java
package com.androidpeople.xml.parsing;
import java.util.ArrayList;
/** Contains getter and setter method for varialbles */
public class SitesList {
/** Variables */
private ArrayList<String> Product = new ArrayList<String>();
private ArrayList<String> Products = new ArrayList<String>();
private ArrayList<String> PriceSet = new ArrayList<String>();
private ArrayList<String> categoryId = new ArrayList<String>();
private ArrayList<String> id= new ArrayList<String>();
private ArrayList<String> title = new ArrayList<String>();
private ArrayList<String> description = new ArrayList<String>();
private ArrayList<String> manufacturer = new ArrayList<String>();
private ArrayList<String> url = new ArrayList<String>();
private ArrayList<String> Image = new ArrayList<String>();
private ArrayList<String> relevancy = new ArrayList<String>();
private ArrayList<String> minPrice = new ArrayList<String>();
private ArrayList<String> maxPrice = new ArrayList<String>();
private ArrayList<String> stores = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getProduct() {
return this.Product;
}
public void setProduct(String Product) {
this.Product.add(Product);
}
public ArrayList<String> getProducts() {
return this.Products;
}
public void setProducts(String Products) {
this.Products.add(Products);
}
public ArrayList<String> getPriceSet() {
return PriceSet;
}
public void setPriceSet(String PriceSet) {
this.PriceSet.add(PriceSet);
}
public void setcategoryId(String categoryId) {
this.categoryId.add(categoryId);
}
public ArrayList<String> getcategoryId() {
return categoryId;
}
public ArrayList<String> getid() {
return id;
}
public void setid(String id) {
this.id.add(id);
}
public ArrayList<String> gettitle() {
return title;
}
public void settitle(String title) {
this.title.add(title);
}
public ArrayList<String> getdescription() {
return description;
}
public void setdescription(String description) {
this.description.add(description);
}
public ArrayList<String> getmanufacturer() {
return manufacturer;
}
public void setmanufacturer(String manufacturer) {
this.manufacturer.add(manufacturer);
}
public ArrayList<String> geturl() {
return url;
}
public void seturl(String url) {
this.url.add(url);
}
public ArrayList<String> getImage() {
return Image;
}
public void setImage(String Image) {
this.Image.add(Image);
}
public ArrayList<String> getrelevancy() {
return relevancy;
}
public void setrelevancy(String relevancy) {
this.relevancy.add(relevancy);
}
public ArrayList<String> getminPrice() {
return minPrice;
}
public void setminPrice(String minPrice) {
this.minPrice.add(minPrice);
}
public ArrayList<String> getmaxPrice() {
return maxPrice;
}
public void setmaxPrice(String maxPrice) {
this.maxPrice.add(maxPrice);
}
public ArrayList<String> getstores() {
return stores;
}
public void setstores(String stores) {
this.stores.add(stores);
}
public void setWebsite(String currentValue) {
// TODO Auto-generated method stub
}
}
//myxmlhandler.java
package com.androidpeople.xml.parsing;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
public static SitesList sitesList = null;
public static SitesList getSitesList() {
return sitesList;
}
public static void setSitesList(SitesList sitesList) {
MyXMLHandler.sitesList = sitesList;
}
/** Called when tag starts ( ex:- <name>AndroidPeople</name>
* -- <name> )*/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if (localName.equals("ProductResponse"))
{
//** Start *//*
sitesList = new SitesList();
} else if (localName.equals("Products")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("Products");
System.out.println("Data"+attr);
sitesList.setProducts(attr);
}
else if (localName.equals("PriceSet")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("PriceSet");
System.out.println("Data"+attr);
sitesList.setPriceSet(attr);
}
else if (localName.equals("Product")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("categoryId");
System.out.println("Data"+attr);
sitesList.setcategoryId(attr);
/** Get attribute value */
String attr1 = attributes.getValue("id");
System.out.println("Data"+attr);
sitesList.setid(attr);
}else if (localName.equals("title")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("title");
System.out.println("Data"+attr);
sitesList.settitle(attr);
}else if (localName.equals("description")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("description");
System.out.println("Data"+attr);
sitesList.setdescription(attr);
}else if (localName.equals("manufacturer")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("manufacturer");
System.out.println("Data"+attr);
sitesList.setmanufacturer(attr);
}else if (localName.equals("url")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("url");
System.out.println("Data"+attr);
sitesList.seturl(attr);
}else if (localName.equals("Image")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("Image");
System.out.println("Data"+attr);
sitesList.setImage(attr);
}else if (localName.equals("relevancy")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("relevancy");
System.out.println("Data"+attr);
sitesList.setrelevancy(attr);
}else if (localName.equals("minPrice")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("minPrice");
System.out.println("Data"+attr);
sitesList.setminPrice(attr);
}else if (localName.equals("maxPrice")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("maxPrice");
System.out.println("Data"+attr);
sitesList.setmaxPrice(attr);
}else if (localName.equals("stores")) {
sitesList = new SitesList();
/** Get attribute value */
String attr = attributes.getValue("stores");
System.out.println("Data"+attr);
sitesList.setstores(attr);
}
}
/** Called when tag closing ( ex:- <name>AndroidPeople</name>
* -- </name> )*/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
/** set value */
if (localName.equalsIgnoreCase("title"))
sitesList.settitle(currentValue);
else if (localName.equalsIgnoreCase("description"))
sitesList.setdescription(currentValue);
}
/** Called to get tag characters ( ex:- <name>AndroidPeople</name>
* -- to get AndroidPeople Character ) */
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
//myparsingexample.java
package com.androidpeople.xml.parsing;
import java.net.URL;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XMLParsingExample extends Activity {
/** Create Object For SiteList Class */
SitesList sitesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
/** Create a new textview array to display the results */
TextView Product[];
TextView categoryId[];
TextView id[];
TextView title[];
TextView description[];
TextView manufacturer[];
TextView url[];
TextView Image[];
TextView relevancy[];
TextView minPrice[];
TextView maxPrice[];
TextView stores[];
TextView Products[];
TextView PriceSet[];
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://catalog.bizrate.com/services/catalog/v1/us/product?publisherId=50085&placementId=1&categoryId=1&keyword=ipod&productId=&productIdType=SZPID&merchantId=&minPrice=&maxPrice=&start=0&results=10&startOffers=0&resultsOffers=0&sort=relevancy_desc&brandId=&attFilter=&showAttributes=&showProductAttributes=&zipCode=&offersOnly=&biddedOnly=&minRelevancyScore=100&apiKey=58f536aa2fab110bbe0da501150bac1e");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
Product = new TextView[sitesList.getProduct().size()];
categoryId = new TextView[sitesList.getcategoryId().size()];
Products = new TextView[sitesList.getProducts().size()];
PriceSet = new TextView[sitesList.getPriceSet().size()];
id = new TextView[sitesList.getid().size()];
title = new TextView[sitesList.gettitle().size()];
manufacturer = new TextView[sitesList.getmanufacturer().size()];
description = new TextView[sitesList.getdescription().size()];
Image = new TextView[sitesList.getImage().size()];
relevancy = new TextView[sitesList.getrelevancy().size()];
minPrice = new TextView[sitesList.getminPrice().size()];
maxPrice = new TextView[sitesList.getmaxPrice().size()];
stores = new TextView[sitesList.getstores().size()];
url = new TextView[sitesList.geturl().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getProduct().size(); i++) {
Product[i] = new TextView(this);
Product[i].setText("Products = "+sitesList.getProducts().get(i));
Products[i] = new TextView(this);
Products[i].setText("Products = "+sitesList.getProducts().get(i));
PriceSet[i] = new TextView(this);
PriceSet[i].setText("PriceSet = "+sitesList.getPriceSet().get(i));
categoryId[i] = new TextView(this);
categoryId[i].setText("categoryId = "+sitesList.getcategoryId().get(i));
id[i] = new TextView(this);
id[i].setText(" id = "+sitesList.getid().get(i));
title[i] = new TextView(this);
title[i].setText("title = "+sitesList.gettitle().get(i));
description[i] = new TextView(this);
description[i].setText("description = "+sitesList.getdescription().get(i));
manufacturer[i] = new TextView(this);
manufacturer[i].setText(" manufacturer = "+sitesList.getmanufacturer().get(i));
url[i] = new TextView(this);
url[i].setText("url = "+sitesList.geturl().get(i));
Image[i] = new TextView(this);
Image[i].setText("Image = "+sitesList.getImage().get(i));
relevancy[i] = new TextView(this);
relevancy[i].setText(" relevancy = "+sitesList.getrelevancy().get(i));
minPrice[i] = new TextView(this);
minPrice[i].setText("minPrice = "+sitesList.getminPrice().get(i));
maxPrice[i] = new TextView(this);
maxPrice[i].setText("maxPrice = "+sitesList.getmaxPrice().get(i));
stores[i] = new TextView(this);
stores[i].setText(" id = "+sitesList.getstores().get(i));
layout.addView(Product[i]);
layout.addView(categoryId[i]);
layout.addView(id[i]);
layout.addView(title[i]);
layout.addView(description[i]);
layout.addView(manufacturer[i]);
layout.addView(url[i]);
layout.addView(Image[i]);
layout.addView(relevancy[i]);
layout.addView(minPrice[i]);
layout.addView(maxPrice[i]);
layout.addView(stores[i]);
layout.addView(description[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}
The value is not coming in ddms also?
check this answer out: Parsing XML
Its a very nice post, explains XML parsing with two approaches, in detail.
i have a xml file
<?xml version="1.0" encoding="utf-8"?>
<NewDataSet> <Password>abcd</Password> </NewDataSet>
how to get the string "abcd" from the above xml file .
I am very new to android platform, please help me out
thanks in advance
From your comment and question, i will suggest you to refer this links:
http://www.anddev.org/parsing_xml_from_the_net_-_using_the_saxparser-t353.html
http://www.ibm.com/developerworks/opensource/library/x-android/
http://www.androidpeople.com/android-xml-parsing-tutorial-%E2%80%93-using-domparser
From first link, you can go step-by-step and second link includes examples for all the parsing techniques.
I suggest to go with SAX(Simple API for XML) Parser.
in my opinion it's easier to understand something via an example, and even more, if we know example what we expect from that example to do.
So I'll post a little sample, which does nothing else but what you need: reads the password from that xml file and returns it in it's readPassword() method:
import java.io.StringReader;
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;
public class XmlSample
{
private static final String xmlSource =
"<?xml version='1.0' encoding='utf-8'?>" +
"<NewDataSet>" +
" <Password>abcd</Password>" +
"</NewDataSet>";
public final class MyXmlHandler extends DefaultHandler
{
/**
* the Password tag's value
*/
private String password;
/**
* for keeping track where the cursor is right now
*/
private String currentNodeName;
public MyXmlHandler()
{
}
/**
* It is called when starting to process a new element (tag)
* At this point you change the currentNodeName member
*/
#Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException
{
this.currentNodeName = localName;
}
/**
* It is called when an element's processing has finished
* ("</ _tag>" or "... />" is reached)
* Clear the currentNodeName member
*/
#Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException
{
this.currentNodeName = null;
}
/**
* It is called when the currentNodeName tag's body is processed.
* In the ch[] array are the character values of that element.
*/
#Override
public void characters(char ch[], int start, int length)
{
if (this.currentNodeName.equals("Password"))
password = new String(ch, start, length);
}
public String getPassword()
{
return password;
}
}
public String readPassword() throws Exception
{
//create an inputSource from the xml value;
//when you get this xml from the server via http, you should use something like:
//HttpEntity responseEntity = response.getEntity();
//final InputSource input = new InputSource(responseEntity.getContent());
final InputSource input = new InputSource(new StringReader(xmlSource));
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
SAXParser parser = parserFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
MyXmlHandler myHandler = new MyXmlHandler();
//attach your handler to the reader
reader.setContentHandler(myHandler);
//parse the input InputSource. It will fill your myHandler instance
reader.parse(input);
return myHandler.getPassword();
}
}
The code itself is pretty small, i just inserted some comments for better understanding.
Let me know if you need more help.