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();
}
}
}
Related
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)
hei guys. i'm quite new in Android programming. I'm trying to get an RSS feed from a website using tutorial i got from the internet. however, when i change the URL to the website id, desired, the program won't show anything and this error appear.
01-13 17:09:30.251: ERROR/RSS Handler IO(277): Too many redirects >> java.net.ProtocolException: Too many redirects
Here is my RSSReader.java page
/**
*
*/
package com.tmm.android.rssreader.reader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.text.Html;
import android.util.Log;
import com.tmm.android.rssreader.util.Article;
import com.tmm.android.rssreader.util.RSSHandler;
/**
* #author rob
*
*/
public class RssReader {
private final static String BOLD_OPEN = "<B>";
private final static String BOLD_CLOSE = "</B>";
private final static String BREAK = "<BR>";
private final static String ITALIC_OPEN = "<I>";
private final static String ITALIC_CLOSE = "</I>";
private final static String SMALL_OPEN = "<SMALL>";
private final static String SMALL_CLOSE = "</SMALL>";
/**
* This method defines a feed URL and then calles our SAX Handler to read the article list
* from the stream
*
* #return List<JSONObject> - suitable for the List View activity
*/
public static List<JSONObject> getLatestRssFeed(){
//String feed = "http://globoesporte.globo.com/dynamo/futebol/times/vasco/rss2.xml";
String feed = "http://www.flightstats.com/go/rss/flightStatusByRoute.do?guid=34b64945a69b9cac:-420d81e6:134c55649d7:-21c5&departureCode=cgk&arrivalCode=sub&departureDate=2012-01-13";
RSSHandler rh = new RSSHandler();
List<Article> articles = rh.getLatestArticles(feed);
Log.e("RSS ERROR", "Number of articles " + articles.size());
return fillData(articles);
}
/**
* This method takes a list of Article objects and converts them in to the
* correct JSON format so the info can be processed by our list view
*
* #param articles - list<Article>
* #return List<JSONObject> - suitable for the List View activity
*/
private static List<JSONObject> fillData(List<Article> articles) {
List<JSONObject> items = new ArrayList<JSONObject>();
for (Article article : articles) {
JSONObject current = new JSONObject();
try {
buildJsonObject(article, current);
} catch (JSONException e) {
Log.e("RSS ERROR", "Error creating JSON Object from RSS feed");
}
items.add(current);
}
return items;
}
/**
* This method takes a single Article Object and converts it in to a single JSON object
* including some additional HTML formating so they can be displayed nicely
*
* #param article
* #param current
* #throws JSONException
*/
private static void buildJsonObject(Article article, JSONObject current) throws JSONException {
String title = article.getTitle();
String description = article.getDescription();
String date = article.getPubDate();
String imgLink = article.getImgLink();
StringBuffer sb = new StringBuffer();
sb.append(BOLD_OPEN).append(title).append(BOLD_CLOSE);
sb.append(BREAK);
sb.append(description);
sb.append(BREAK);
sb.append(SMALL_OPEN).append(ITALIC_OPEN).append(date).append(ITALIC_CLOSE).append(SMALL_CLOSE);
current.put("text", Html.fromHtml(sb.toString()));
current.put("imageLink", imgLink);
}
}
here is my RSSHandler.java code
package com.tmm.android.rssreader.util;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
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.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class RSSHandler extends DefaultHandler {
// Feed and Article objects to use for temporary storage
private Article currentArticle = new Article();
private List<Article> articleList = new ArrayList<Article>();
// Number of articles added so far
private int articlesAdded = 0;
// Number of articles to download
private static final int ARTICLES_LIMIT = 20;
//Current characters being accumulated
StringBuffer chars = new StringBuffer();
/*
* This method is called everytime a start element is found (an opening XML marker)
* here we always reset the characters StringBuffer as we are only currently interested
* in the the text values stored at leaf nodes
*
* (non-Javadoc)
* #see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String uri, String localName, String qName, Attributes atts) {
chars = new StringBuffer();
}
/*
* This method is called everytime an end element is found (a closing XML marker)
* here we check what element is being closed, if it is a relevant leaf node that we are
* checking, such as Title, then we get the characters we have accumulated in the StringBuffer
* and set the current Article's title to the value
*
* If this is closing the "Item", it means it is the end of the article, so we add that to the list
* and then reset our Article object for the next one on the stream
*
*
* (non-Javadoc)
* #see org.xml.sax.helpers.DefaultHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
if (localName.equalsIgnoreCase("title"))
{
Log.d("LOGGING RSS XML", "Setting article title: " + chars.toString());
currentArticle.setTitle(chars.toString());
}
else if (localName.equalsIgnoreCase("description"))
{
Log.d("LOGGING RSS XML", "Setting article description: " + chars.toString());
currentArticle.setDescription(chars.toString());
}
else if (localName.equalsIgnoreCase("pubDate"))
{
Log.d("LOGGING RSS XML", "Setting article published date: " + chars.toString());
currentArticle.setPubDate(chars.toString());
}
else if (localName.equalsIgnoreCase("encoded"))
{
Log.d("LOGGING RSS XML", "Setting article content: " + chars.toString());
currentArticle.setEncodedContent(chars.toString());
}
//////////////////
else if(localName.equalsIgnoreCase("fh:FlightHistory"))
{
Log.d("LOGGING RSS XML", "Setting article content: " + chars.toString());
currentArticle.setFhFlightHistory(chars.toString());
}
else if(localName.equalsIgnoreCase("fh:Airline"))
{
Log.d("LOGGING RSS XML", "Setting article content: " + chars.toString());
currentArticle.setFhAirline(chars.toString());
}
////////////////////
else if (localName.equalsIgnoreCase("item"))
{
}
else if (localName.equalsIgnoreCase("link"))
{
try {
System.out.println(chars.toString());
Log.d("LOGGING RSS XML", "Setting article link url: " + chars.toString());
currentArticle.setUrl(new URL(chars.toString()));
} catch (MalformedURLException e) {
Log.e("RSA Error", e.getMessage());
e.printStackTrace();
}
}
// Check if looking for article, and if article is complete
if (localName.equalsIgnoreCase("item")) {
articleList.add(currentArticle);
currentArticle = new Article();
// Lets check if we've hit our limit on number of articles
articlesAdded++;
if (articlesAdded >= ARTICLES_LIMIT)
{
throw new SAXException();
}
}
}
/*
* This method is called when characters are found in between XML markers, however, there is no
* guarante that this will be called at the end of the node, or that it will be called only once
* , so we just accumulate these and then deal with them in endElement() to be sure we have all the
* text
*
* (non-Javadoc)
* #see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
*/
public void characters(char ch[], int start, int length) {
chars.append(new String(ch, start, length));
}
/**
* This is the entry point to the parser and creates the feed to be parsed
*
* #param feedUrl
* #return
*/
public List<Article> getLatestArticles(String feedUrl) {
URL url = null;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString());
} catch (SAXException e) {
Log.e("RSS Handler SAX", e.toString());
} catch (ParserConfigurationException e) {
Log.e("RSS Handler Parser Config", e.toString());
}
return articleList;
}
}
Please, any answer and suggest will be so much appreciated. :)
It is most likely a user-agent related problem.
As far as I see it, the site you are calling has a special version for mobiles, and won't give you the RSS feed if it detects that you are using a mobile user agent.
You probably need to change it.
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 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
guys I have a problem in my program that it returns an Exception as Unable to start activity and gives Force Close to my applicatio of Xml Parsing. Please review my code and help me.
code: package com.ex.createXml;
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 SitesList Class*/
SitesList siteslist = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(1);
TextView name[];
TextView websites[];
TextView category[];
try{
/*Handling Xml*/
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
URL sourceurl = new URL("http://www.androidpeople.com/wp-content/uploads/2010/06/example.xml");
MyXmlHandler mxh = new MyXmlHandler();
xr.setContentHandler(mxh);
xr.parse(new InputSource(sourceurl.openStream()));
}catch(Exception e)
{
System.out.println("Xml Parsing Exception="+e);
}
siteslist = MyXmlHandler.siteslist;
name = new TextView[siteslist.getName().size()];
websites = new TextView[siteslist.getWebsite().size()];
category = new TextView[siteslist.getCategory().size()];
/** Set the result text in textview and add it to layout */
for (int i = 0; i < siteslist.getWebsite().size(); i++) {
name[i] = new TextView(this);
name[i].setText("Name = "+siteslist.getName().get(i));
websites[i] = new TextView(this);
websites[i].setText("Website = "+siteslist.getWebsite().get(i));
category[i] = new TextView(this);
category[i].setText("Website Category = "+siteslist.getCategory().get(i));
layout.addView(name[i]);
layout.addView(websites[i]);
layout.addView(category[i]);
}
setContentView(layout);
}
}
have u mentioned xmlParsingExample in manifeast file or not.as this is from android people & it will work fine so just check have u mentioned in manifeast or not.
Independently of your xml parsing, did you set internet permission for your activity (in the manifest)? See the android dev doc and set android.permission.INTERNET.
You try to get an xml file on http. As a consequence, if you don't allow the application to use internet…