How to Display XML-parsing using sax - android

I want to create xml parsing using SAX of this URL
http://news.google.com/?output=rss
but I got the error please check and let me know where I do mistake or If there is another solutions for my problem.
I got error in GoogleNewsSaxActivity.class at this line
for (int i = 0; i < baseParserData.getTitle().size(); i++) {
My code is as per below.
GoogleNewsSaxActivity.class
public class GoogleNewsSaxActivity extends Activity {
BaseFeedParser baseParserData;
ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
private myAdapter rssadaptor = null;
ListView lview;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
SAXParserFactory saxPF = SAXParserFactory.newInstance();
SAXParser saxP = saxPF.newSAXParser();
XMLReader xmlR = saxP.getXMLReader();
URL url = new URL("http://news.google.com/?output=rss");
RssHandler myXMLHandler = new RssHandler();
xmlR.setContentHandler(myXMLHandler);
xmlR.parse(new InputSource(url.openStream()));
} catch (Exception e) {
System.out.println(e);
}
baseParserData = RssHandler.baseParserData;
/**
* Run a for loop to set All the TextViews with text until
* the size of the array is reached.
*
**/
for (int i = 0; i < baseParserData.getTitle().size(); i++) {
System.out.println("value of i==============>" + i);
HashMap<String, String> map = new HashMap<String, String>();
map.put("title", baseParserData.getTitle().get(i));
//map.put("Artist", baseParserData.getArtist().get(i));
//map.put("Contry", baseParserData.getCountry().get(i));
items.add(map);
rssadaptor = new myAdapter(GoogleNewsSaxActivity.this, items);
}
lview = (ListView) findViewById(R.id.listView);
// Getting adapter by passing xml data ArrayList
rssadaptor = new myAdapter(this, items);
lview.setAdapter(rssadaptor);
}
}
RssHandler.class
public class RssHandler extends DefaultHandler{
/*private List<BaseFeedParser> messages;
//private Message currentMessage;
private StringBuilder builder;*/
String elementValue = null;
Boolean elementOn = false;
public static BaseFeedParser baseParserData = null;
public static BaseFeedParser getBaseParserData() {
return baseParserData;
}
public static void setBaseParserData(BaseFeedParser baseParserData) {
RssHandler.baseParserData = baseParserData;
}
/*public List<BaseFeedParser> getMessages(){
return this.messages;
}*/
#Override
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
elementOn = true;
System.out.println("Hello this is startElement : =========>");
if (localName.equals(BaseFeedParser.CHANNEL))
{
baseParserData = new BaseFeedParser();
} else if (localName.equals(BaseFeedParser.ITEM)) {
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase(BaseFeedParser.TITLE))
baseParserData.setTitle(elementValue);
else if (localName.equalsIgnoreCase(BaseFeedParser.LINK))
baseParserData.setLink(elementValue);
else if (localName.equalsIgnoreCase(BaseFeedParser.PUB_DATE))
baseParserData.setPubDate(elementValue);
else if (localName.equalsIgnoreCase(BaseFeedParser.DESCRIPTION))
baseParserData.setDescription(elementValue);
}
}
And also there are two another class BaseFeedParser.class and myAdapter.class , BaseFeedParser class contain the Getters/Setters metods and myadapter is adapter class for the custom listview.
Thanks.
Display error In LOGCAT
05-31 09:42:25.693: I/System.out(279): java.net.SocketException: Permission denied
05-31 09:42:25.713: D/AndroidRuntime(279): Shutting down VM
05-31 09:42:25.713: W/dalvikvm(279): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-31 09:42:25.752: E/AndroidRuntime(279): FATAL EXCEPTION: main
05-31 09:42:25.752: E/AndroidRuntime(279): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rahul.android.sax/com.rahul.android.sax.GoogleNewsSaxActivity}: java.lang.NullPointerException
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.os.Handler.dispatchMessage(Handler.java:99)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.os.Looper.loop(Looper.java:123)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-31 09:42:25.752: E/AndroidRuntime(279): at java.lang.reflect.Method.invokeNative(Native Method)
05-31 09:42:25.752: E/AndroidRuntime(279): at java.lang.reflect.Method.invoke(Method.java:521)
05-31 09:42:25.752: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-31 09:42:25.752: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-31 09:42:25.752: E/AndroidRuntime(279): at dalvik.system.NativeStart.main(Native Method)
05-31 09:42:25.752: E/AndroidRuntime(279): Caused by: java.lang.NullPointerException
05-31 09:42:25.752: E/AndroidRuntime(279): at com.rahul.android.sax.GoogleNewsSaxActivity.onCreate(GoogleNewsSaxActivity.java:61)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-31 09:42:25.752: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-31 09:42:25.752: E/AndroidRuntime(279): ... 11 more

Use Below Code for that.
SitesList.java
public class SitesList {
/** Variables */
private ArrayList<String> name = new ArrayList<String>();
private ArrayList<String> website = new ArrayList<String>();
private ArrayList<String> pubdate = new ArrayList<String>();
private ArrayList<String> desc = 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);
}
public ArrayList<String> getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website.add(website);
}
public ArrayList<String> getPubdate() {
return pubdate;
}
public void setPubdate(String pubdate) {
this.pubdate.add(pubdate);
}
public ArrayList<String> getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc.add(desc);
}
}
MyXMLHandler.java
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("channel")) {
/** Start */
sitesList = new SitesList();
}
}
/**
* 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.setName(currentValue);
} else if (localName.equalsIgnoreCase("link")) {
sitesList.setWebsite(currentValue);
} else if (localName.equalsIgnoreCase("pubDate")) {
sitesList.setPubdate(currentValue);
} else if (localName.equalsIgnoreCase("description")) {
sitesList.setDesc(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;
}
}
}
MainActivity.java
public class MainActivity extends Activity {
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 name[];
TextView website[];
TextView pubdate[];
TextView desc[];
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://news.google.com/?output=rss");
/** 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 Exception = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
/** Assign textview array lenght by arraylist size */
name = new TextView[sitesList.getName().size()];
website = new TextView[sitesList.getWebsite().size()];
pubdate = new TextView[sitesList.getPubdate().size()];
desc = new TextView[sitesList.getDesc().size()];
System.out.println("Hello Name size is:- " +sitesList.getName().size());
System.out.println("Hello website size is:- " +sitesList.getWebsite().size());
System.out.println("Hello pubdate size is:- " +sitesList.getPubdate().size());
System.out.println("Hello desc size is:- " +sitesList.getDesc().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 is = " + sitesList.getName().get(i));
website[i] = new TextView(this);
website[i].setText("Link is = " + sitesList.getWebsite().get(i));
layout.addView(name[i]);
layout.addView(website[i]);
}
/** Set the result text in textview and add it to layout */
for (int i = 0; i < sitesList.getPubdate().size(); i++) {
pubdate[i] = new TextView(this);
pubdate[i].setText("Pub date is = "
+ sitesList.getPubdate().get(i));
desc[i] = new TextView(this);
desc[i].setText("Desc is = "
+ sitesList.getDesc().get(i));
layout.addView(pubdate[i]);
layout.addView(desc[i]);
}
/** Set the layout view to display */
setContentView(layout);
}
}

Related

Android asynctask exception

i'm doing an app that have to get an XML file from an url and parse it. I always find this log cat (PS:i can't find the correct google prettify sintax code highlighting):
11-06 23:12:44.940: E/Trace(8751): error opening trace file: No such file or directory(2)
11-06 23:12:51.345: E/Error:(8751): expected: /hr read: body (position:END_TAG </body>#6:8 in java.io.StringReader#431887b8)
11-06 23:12:51.360: E/AndroidRuntime(8751): FATAL EXCEPTION: AsyncTask #1
11-06 23:12:51.360: E/AndroidRuntime(8751): java.lang.RuntimeException: An error occured while executing doInBackground()
11-06 23:12:51.360: E/AndroidRuntime(8751): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-06 23:12:51.360: E/AndroidRuntime(8751): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.lang.Thread.run(Thread.java:856)
11-06 23:12:51.360: E/AndroidRuntime(8751): Caused by: java.lang.NullPointerException
11-06 23:12:51.360: E/AndroidRuntime(8751): at com.ambro.app.Update$connection.doInBackground(Update.java:39)
11-06 23:12:51.360: E/AndroidRuntime(8751): at com.ambro.app.Update$connection.doInBackground(Update.java:1)
11-06 23:12:51.360: E/AndroidRuntime(8751): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-06 23:12:51.360: E/AndroidRuntime(8751): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-06 23:12:51.360: E/AndroidRuntime(8751): ... 5 more
the xml could be found at: http://www.lookedpath.tk/apps/firstapp/version.xml
the update.java code:
public class Update extends Activity {
private TextView testo2;
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.update);
super.onCreate(savedInstanceState);
testo2= (TextView) findViewById(R.id.textView2);
}
public void goToUpdate (View view) {
System.out.println("ciao");
new connection().execute();
}
public class connection extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
boolean updated=false;
String lastversion=null;
Element e=null;
final String URL = "http://www.lookedpath.tk/apps/firstapp/version.xml";
final String VERSION = "version";
final String APPLICATION = "application";
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(APPLICATION);
for (int i=0;i<nl.getLength();i++) {
e = (Element) nl.item(0);
lastversion = parser.getValue(e, VERSION); // name child value
}
String actver = getString(R.string.version);
if(actver==lastversion) updated=true;
return updated;
}
protected void onPostExecute(Boolean... result) {
if(result[0]==false){
testo2.setText(R.string.newversion);
} else {
testo2.setText(R.string.nonewversion);
}
}
};
}
so this is the xmlparser.java file:
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
}
the logcat say that the error is in the line 39 of the update class:
NodeList nl = doc.getElementsByTagName(APPLICATION);
but i can't manage to resolve the problem. can anyone help me?
UPDATE:
i have fixed the error 405 but i still have a null pointer exception. i found that the program run correctly but never enter in the post execute method because of this exception..
I have tried your code there is not any problem, it is fine. Problem is in the link.
In browser it looks like this
<?xml version="1.0" encoding="UTF-8"?>
<menu>
<application>
<version>1.5</version>
</application>
</menu>
But when i print xml variable it give me
<html>
<head><title>405 Not Allowed</title></head>
<body bgcolor="white">
<center><h1>405 Not Allowed</h1></center>
<hr><center>nginx</center>
</body>
</html>
and then in dom variable you got null and when you try to find element in nl variable which is null you got error..,.
I tried your code with some other xml feed it works great..,.
Hey have a look on my Library.
You can easily manipulate XML with it ;)
From the logs, I can see you have a NullPointer in Update.java, line 39. You can start from there. I believe it's not related to AsyncTask.
You can check this link for xml parsing from xml.
http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/
In your activity you are developing the AsyncTask but you forgot to override onPreExecute method. See this example for how to develop AsyncTask in your activity.
package com.androidhive.jsonparsing;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AndroidJSONParsingActivity extends ListActivity {
// url to make request
private static String url = "http://api.androidhive.info/contacts/";
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// contacts JSONArray
JSONArray contacts = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new GetEventsTask().execute("");
}
protected class GetEventsTask extends
AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
protected ArrayList<HashMap<String, String>> contactList;
private final ProgressDialog dialog = new ProgressDialog(
AndroidJSONParsingActivity.this);
//PreExecute Method
protected void onPreExecute() {
this.dialog.setMessage("Loading, Please Wait..");
this.dialog.setCancelable(false);
this.dialog.show();
}
//doInBackground Method
#Override
protected ArrayList<HashMap<String, String>> doInBackground(
String... params) {
contactList = new ArrayList<HashMap<String, String>>();
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.i("json objects",""+json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
try {
// Getting Array of Contacts
contacts = jObj.getJSONArray(TAG_CONTACTS);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
String address = c.getString(TAG_ADDRESS);
String gender = c.getString(TAG_GENDER);
// Phone number is agin JSON Object
JSONObject phone = c.getJSONObject(TAG_PHONE);
String mobile = phone.getString(TAG_PHONE_MOBILE);
String home = phone.getString(TAG_PHONE_HOME);
String office = phone.getString(TAG_PHONE_OFFICE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_EMAIL, email);
map.put(TAG_PHONE_MOBILE, mobile);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
return contactList;
}
//onPostExecute Method
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
ListAdapter adapter = new SimpleAdapter(getApplicationContext(),
contactList, R.layout.list_item, new String[] { TAG_NAME,
TAG_EMAIL, TAG_PHONE_MOBILE }, new int[] {
R.id.name, R.id.email, R.id.mobile });
// selecting single ListView item
ListView lv = getListView();
lv.setAdapter(adapter);
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),SingleMenuItemActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
}
you get just null xml at that position so debuge your application first check any xml responce u get or not????
if u get null xml then use following code for parse xml
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 {
String elementValue = null;
Boolean elementOn = false;
userdata d = userdata.getInstance();
public static XMLGettersSetters data = null;
public static XMLGettersSetters getXMLData() {
return data;
}
public static void setXMLData(XMLGettersSetters data) {
XMLHandler.data = data;
}
/**
* This will be called when the tags of the XML starts.
**/
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
elementOn = true;
if (localName.equals("application"))
{
data = new XMLGettersSetters();
}
}
/**
* This will be called when the tags of the XML end.
**/
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
elementOn = false;
/**
* Sets the values after retrieving the values from the XML tags
* */
if (localName.equalsIgnoreCase("version")){
System.out.println("ststus" + elementValue);
d.setIsregi(elementValue);
}
/**
* This is called to get the tags value
**/
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (elementOn) {
elementValue = new String(ch, start, length);
elementOn = false;
}
}
}
You have to add the correct DTD to your xml (Document Type Definition) , try it and you will see that the parsing will run smooth .
Step 1 : Generate correcte DTD
Step 2 : Add it to your xml file and save it
Step 3 : upload your xml file , parse it and enjoy .

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 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?

Android: parse XML from string problems

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

sax parsing through url in android

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.

Categories

Resources