Android: parse XML from string problems - android

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) {
}

Related

XML Parser returns only first item

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

NullPointException when parsing xml in android

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)

How to get data using SAX parsing in android

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;
}
}

how to display image in grid view reading imageUrl from xml using sax parser in android

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

How to draw a route by parsing xml to google map on android

How can i parse the XML file in URL that contains latitude and longitude which i will draw a route using this coordinates
Here is the xml file
<tgt_api>
<tgt_trip>
<id>1</id>
<tgt_tourist>
<id>1</id>
<firstname>tourist1</firstname>
<lastname>touristlname</lastname>
<passport_id>123fjkl34552</passport_id>
<country>United States</country>
<telephone>08912345678</telephone>
</tgt_tourist>
<tgt_taxi>
<license_id/>
<firstname/>
<lastname/>
<mobile/>
<license_plate/>
</tgt_taxi>
<tgt_destination>
<place_name>Ladkrabang</place_name>
<destination_point>
<lat>13.72331</lat>
<lng>100.78453999999999</lng>
</destination_point>
<routes>
<point counter="1">
<lat>13.692941</lat>
<lng>100.750723</lng>
</point>
<point counter="2">
<lat>13.71347</lat>
<lng>100.75589000000002</lng>
</point>
<point counter="3">
<lat>13.71329</lat>
<lng>100.75553000000002</lng>
</point>
<point counter="4">
<lat>13.70851</lat>
<lng>100.77463999999998</lng>
</point>
<point counter="5">
<lat>13.7218</lat>
<lng>100.77636000000007</lng>
</point>
<point counter="6">
<lat>13.72206</lat>
<lng>100.78467</lng>
</point>
<point counter="7">
<lat>13.72284</lat>
<lng>100.78467</lng>
</point>
<point counter="8">
<lat>13.72331</lat>
<lng>100.78453999999999</lng>
</point>
</routes>
</tgt_destination>
when click the button it will go to this method
private void parseXML() {
contents="http://10.0.2.2/AirportWebApplication/tgt_api.php?trip_id=1";
try {
/* Create a URL we want to load some xml-data from. */
URL url = new URL(contents);
InputStream in = url.openStream();
InputSource is = new InputSource(in);
/* 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 */
handler = new XMLHandler();
xr.setContentHandler(handler);
/* Parse the xml-data from our URL. */
xr.parse(is);
/* Parsing has finished. */
/* Our ExampleHandler now provides the parsed data to us. */
maplist = handler.getParsedData();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void routeMap(ArrayList<MapPoint> points){
for (int i = 0; i<points.size()-1;i++){
TGT3.this.drawPath(points.get(i), points.get(i+1),Color.GREEN);
}
}
private void drawPath(MapPoint mapPoint, MapPoint mapPoint2,int color) {
// TODO Auto-generated method stub
GeoPoint gp1 = new GeoPoint((int)(mapPoint.getCoor()[0]),(int)(mapPoint.getCoor()[1]));
GeoPoint gp2 = new GeoPoint((int)(mapPoint2.getCoor()[0]),(int)(mapPoint2.getCoor()[1]));
mapView.getOverlays().add(new RouteOverlay(gp1,gp2,color));
}
and XMLHandler class
package com.TouristNavigation;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHandler extends DefaultHandler {
private MapPoints MapList = new MapPoints();
private String latitude, longitude;
private boolean inRouteTag;
private boolean inPointTag;
private boolean inLatTag;
private boolean inLongTag;
private int index = 0;
public ArrayList<MapPoint> getParsedData() {
// return this.myParsedExampleDataSet;
return MapList.getAllPoint();
}
#Override
public void startDocument() throws SAXException {
// this.myParsedExampleDataSet = new ParsedExampleDataSet();
MapList = new MapPoints();
}
#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, Attributes attributes) throws SAXException
{
if (localName.equals("routes")) {
inRouteTag = true;
}
if (localName.equals("point")) {
inPointTag = true;
}
if (localName.equals("lat")) {
inLatTag = true;
}
if (localName.equals("lng")) {
inLongTag = true;
}
}
/**
* Gets be called on closing tags like: </tag>
*/
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("lat")) {
inLatTag = false;
}
if (localName.equals("lng")) {
inLongTag = false;
}
if (localName.equals("point")) {
//MapPoint i = new MapPoint(Double.parseDouble(latitude),Double.parseDouble(longitude));
MapPoint i = new MapPoint(Double.parseDouble(latitude),Double.parseDouble(longitude));
Log.e(latitude+" "+longitude, getClass().getSimpleName());
MapList.addPoint(i);
inPointTag = false;
clearInfo();
}
}
private void clearInfo(){
latitude = "";
longitude = "";
}
/**
* Gets be called on the following structure: <tag>characters</tag>
*/
#Override
public void characters(char ch[], int start, int length) {
if(inLatTag){
latitude = new String(ch, start, length);
}
if (inLongTag) {
longitude = new String(ch, start, length);
}
}
}
but after i test it, it got an error at XMLhandler class
ERROR : NUMBERFORMATEXCEPTION
what have i done wrong?, is there any suggestion?

Categories

Resources