I followed a tutorial to learn to parse the data from the gpx file (which is in my raw folder), and for some reason no data is getting parsed into the NodeList. Here is my XMLParser class
package bry.Bicker.OjaiHiking;
import java.io.IOException;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
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 e, String str) {
NodeList n = e.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 "";
}
}
Here is how I am attempting to use the class to parse the file:
public void displayPoints(MapView map, Context context) {
final String KEY_TRKPT = "trkpt";
final String KEY_LAT = "lat";
final String KEY_LON = "lon";
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(getString(R.raw.test));
NodeList n1 = doc.getElementsByTagName(KEY_TRKPT);
if (n1.getLength() > 0) {
int[] lat = new int[n1.getLength()];
int[] lon = new int[n1.getLength()];
for (int i = 0; i < n1.getLength(); i++) {
org.w3c.dom.Element e = (org.w3c.dom.Element) n1.item(i);
lat[i] = Integer.parseInt(parser.getValue(e, KEY_LAT));
lon[i] = Integer.parseInt(parser.getValue(e, KEY_LON));
}
} else {
Log.i("Debug", "XML Parsing error. No data in nodelist.");
}
}
and the GPX file was exported from the application "MyTracks."
I get no errors, but my message that states "XML Parsing error. No data in nodelist." is displayed.
There are a few useful libraries out there - including mine. See answer to this other question on StackOverflow. Basically my library provides two ways to parse you GPX file: once you obtain / create a GPXParser object (mParser in the examples below), you can then either parse directly your GPX file
Gpx parsedGpx = null;
try {
InputStream in = getAssets().open("test.gpx");
parsedGpx = mParser.parse(in);
} catch (IOException | XmlPullParserException e) {
e.printStackTrace();
}
if (parsedGpx == null) {
// error parsing track
} else {
// do something with the parsed track
}
or you can parse a remote file:
mParser.parse("http://myserver.com/track.gpx", new GpxFetchedAndParsed() {
#Override
public void onGpxFetchedAndParsed(Gpx gpx) {
if (gpx == null) {
// error parsing track
} else {
// do something with the parsed track
}
}
});
Contributions are welcome.
This open source library is currently being used in an android app, both smartphone side and smartwatch side as well
https://plus.google.com/u/0/communities/110606810455751902142
Usage example
Gpx gpx = GpxFileIo.parseIn( "SomeGeoCollection.gpx" ) ;
for (Point pt: gpx.getPoints( ) )
{
Location loc = new Location( pt.getLatitude( ), pt.getLongitude( ) ) ;
if (pt.getElevation( ) != null) loc.setElevation( pt.getElevation( ) ) ;
}
Related
I using this tutorial http://www.androidbegin.com/tutorial/android-xml-parse-images-and-texts-tutorial/ to reaching XML parsing,if I want to change the url to this one http://gis.taiwan.net.tw/XMLReleaseALL_public/activity_C_f.xml ,how to do that? Because the xml format are different.If there is a similar question of this please inform me.Thanks.
There is a tag in each listitem but my url only 'Infos' at begin which includes all tags.
MainActivity.java
package eason.xml;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
// Declare Variables
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String ID = "Id";
static String NAME = "Name";
static String WEBSITE = "Website";
static String PICTURE1 = "Picture";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadXML().execute();
}
// DownloadJSON AsyncTask
private class DownloadXML extends AsyncTask<Void, Void, Void> {
private void parseRequestResultXML(InputStream stream) {
arraylist=new ArrayList<HashMap<String,String>>();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(stream, null);
HashMap<String, String> map = null;
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (parser.getEventType()) {
case XmlPullParser.START_DOCUMENT:
//Log.i("TAG", " Start document " + parser.getName());
break;
case XmlPullParser.START_TAG:
//Log.i("TAG", " Start tag " + parser.getName());
String tag=parser.getName();
if(tag.equals("Info")){ //read values from Info tag
Log.i("TAG","reading info");
ID=parser.getAttributeValue(null, "Id");
NAME=parser.getAttributeValue(null, "Name");
WEBSITE=parser.getAttributeValue(null, "Website");
PICTURE1=parser.getAttributeValue(null,"Picture1");
//do same for other values
map = new HashMap<String, String>();
map.put("Id", ID);
map.put("Name", NAME);
map.put("Website", WEBSITE);
arraylist.add(map);
}
break;
case XmlPullParser.END_TAG:
//Log.i("TAG", " End tag " + parser.getName());
break;
default:
break;
}
eventType=parser.next(); //get next event type
}
//reading all values from list
for (Map<String,String> e : arraylist) {
Log.d("TAG"," Row ID "+e.get("Id")+" Name "+e.get("Name")+" Website "+e.get("Website")+" Picture1 "+e.get("Picture1"));
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android XML Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
// Retrieve nodes from the given URL address
InputStream stream = parser.getInputStreamFromUrl("http://gis.taiwan.net.tw/XMLReleaseALL_public/activity_C_f.xml");
if (stream != null) {
try {parseRequestResultXML(stream);
stream.close();}catch(IOException e1) {
e1.printStackTrace();
}
}return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Binds the Adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}}
ListViewAdapter
package eason.xml;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView NAME;
TextView START;
TextView WEBSITE;
ImageView Picture1;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
NAME = (TextView) itemView.findViewById(R.id.rank);
START = (TextView) itemView.findViewById(R.id.country);
WEBSITE = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
Picture1 = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
NAME.setText(resultp.get(MainActivity.ID));
START.setText(resultp.get(MainActivity.NAME));
WEBSITE.setText(resultp.get(MainActivity.WEBSITE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.PICTURE1), Picture1);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("Id", resultp.get(MainActivity.ID));
// Pass all data country
intent.putExtra("Name", resultp.get(MainActivity.NAME));
// Pass all data population
intent.putExtra("Website",
resultp.get(MainActivity.WEBSITE));
// Pass all data flag
intent.putExtra("Picture1", resultp.get(MainActivity.PICTURE1));
// Start SingleItemView Class
context.startActivity(intent);
}
});
return itemView;
}
}
XML parser
package eason.xml;
import android.util.Log;
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.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class XMLParser {
public XMLParser() {
}
// Retrive XML from URL
public String getXmlFromUrl(String url) {
String xml = null;
try {
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;
}
// Retrive DOM element
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 doc;
}
// Retrive Node element
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 "";
}
// Retrive Node Value
public InputStream getInputStreamFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Change the URL in getXmlFromUrl() and then change the keys in parser.getValue(e, **RANK**). Whatever your format is, you need to specify the keys to get the data and then save accordingly.
In that tutorial Author is reading values from TEXT tag of XML. But in your case you need to get values from there attribute name.
private void parseRequestResultXML(InputStream stream) {
arraylist=new ArrayList<HashMap<String,String>>();
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(stream, null);
HashMap<String, String> map = null;
int eventType = parser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (parser.getEventType()) {
case XmlPullParser.START_DOCUMENT:
//Log.i("TAG", " Start document " + parser.getName());
break;
case XmlPullParser.START_TAG:
//Log.i("TAG", " Start tag " + parser.getName());
String tag=parser.getName();
if(tag.equals("Info")){ //read values from Info tag
Log.i("TAG","reading info");
String id=parser.getAttributeValue(null, "Id");
String name=parser.getAttributeValue(null, "Name");
String website=parser.getAttributeValue(null, "Website");
//do same for other values
map = new HashMap<String, String>();
map.put("id", id);
map.put("name", name);
map.put("website", website);
arraylist.add(map);
}
break;
case XmlPullParser.END_TAG:
//Log.i("TAG", " End tag " + parser.getName());
break;
default:
break;
}
eventType=parser.next(); //get next event type
}
//reading all values from list
for (Map<String,String> e : arraylist) {
Log.d("TAG"," Row ID "+e.get("id")+" Name "+e.get("name")+" Website "+e.get("website"));
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
UPDATED:
Add this method in XMLParser.java
public InputStream getInputStreamFromUrl(String url) {
String xml = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
In doInBackground
arraylist = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
// Retrieve nodes from the given URL address
InputStream stream = parser.getInputStreamFromUrl("http://www.androidbegin.com/tutorial/xmlparseimgtxt.xml");
if (stream != null){
parseRequestResultXML(stream);
stream.close();
}
I am not able to parse my XML here. It returns "Item" only.
My AndroidActivity cannot be shown as it is very big. That's why I have only shown the part which is responsible for parsing.
My XML Looks like this :
<MyResource>
<Item>First</Item>
<Item>Second</Item>
</MyResource>
My ActivityClass method:
public class ShowItems extends Activity{
ListView lv;
ListAdapter adapter;
static final String KEY_RESOURCE = "MyResource"; // parent node
static final String KEY_ITEM = "Item";
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String[] from={KEY_ITEM };
int[] to={R.id.mylist_item};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.showitems);
lv=(ListView) findViewById(R.id.lv_items);
parseXML();
adapter = new SimpleAdapter(this, mylist,R.layout.list_item,from , to);
lv.setAdapter(adapter);
}
private void parseXML() {
// TODO Auto-generated method stub
XMLParser parser = new XMLParser();
final String URL="http://10.0.2.2:8080/MySite/xml";
String xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_RESOURCE);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ITEM, parser.getValue(e, KEY_ITEM));
mylist.add(map); }
}
My XML Parser Class:
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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;
}
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 "";
}
}
I am not able to parse my XML here. What is the problem here?
It returns "Item" only.
What do I need to do in my ActivityClass especially in this part of the code?
String xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_RESOURCE);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
map.put(KEY_ITEM, parser.getValue(e, KEY_ITEM));
mylist.add(map); }
Your getValue() method gets MyResource element, from there, you need to get all Items under MyResource and do getElementValue(). Example code is:
public Map getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
for (int i = 0; i < n.getLength(); i++) {
System.out.println(getElementValue(n.item(i)));
}
//Here store it in list/map and return list/map instead of String
return list/MapHere;
}
I want to retrieve the image link inside the description tag, my tags are all working, here is the sample of description tag:
[http://news.instaforex.com/analytics/rss][1]
I want to retrieve the image link or to show the image. My question is how to that base on my code below?
mainactivity
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://news.instaforex.com/analytics/rss";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_TITLE = "title";
static final String KEY_PUBDATE = "pubDate";
static final String KEY_DESCRIPTION = "description";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ArrayList<HashMap<String, Spanned>> menuItems = new ` ArrayList<HashMap<String, Spanned>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, Spanned> map = new HashMap<String, Spanned>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, Html.fromHtml(parser.getValue(e, KEY_TITLE)));
map.put(KEY_PUBDATE, Html.fromHtml(parser.getValue(e, KEY_PUBDATE)));
String description = parser.getValue(e, KEY_DESCRIPTION);;
int index = description.indexOf("The material has been provided by InstaForex Company", 0);
description = description.substring(0, index-1);
map.put(KEY_DESCRIPTION, Html.fromHtml(description));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_TITLE, KEY_PUBDATE }, new int[] {
R.id.name, R.id.cost });
setListAdapter(adapter);
((BaseAdapter) adapter).notifyDataSetChanged();
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String title = menuItems.get(position).get(KEY_TITLE).toString();
String pubDate = menuItems.get(position).get(KEY_PUBDATE).toString();
String description= menuItems.get(position).get(KEY_DESCRIPTION).toString();
System.out.println("PubDate==>"+pubDate+"\n Description===>"+description);
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_TITLE, title);
in.putExtra(KEY_PUBDATE, pubDate);
in.putExtra(KEY_DESCRIPTION, description);
startActivity(in);
}
});
}
}
xmlparser
package com.androidhive.xmlparsing;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.text.Html;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
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;
}
/**
* Getting XML DOM element
* #param XML string
* */
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setCoalescing(true);
dbf.setNamespaceAware(true);
if (dbf.isNamespaceAware()==Boolean.TRUE) {
dbf.setNamespaceAware(Boolean.FALSE);
}
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 doc;
}
/** Getting node value
* #param elem element
*/
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 || child.getNodeType() == Node.CDATA_SECTION_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
I'm trying to make an app that parses an RSS feed. I run my app but the fetching of data is very slow although the source link ( http://api.androidhive.info/music/music.xml ) is very fast.
I need my app to respond quickly.
My app code :
package com.sta.map;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
public class POSTS extends Activity {
static final String KEY_ARTIST = "artist";
static final String KEY_THUMB_URL = "thumb_url";
ListView list;
WbAdapter adapter;
static String URL = "http://api.androidhive.info/music/music.xml";
ProgressDialog pDialog;
ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.posts);
new ParseXMLTask().execute();
}
class ParseXMLTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
// Showing progress dialog before sending http request
pDialog = new ProgressDialog(POSTS.this);
pDialog.setMessage("Please wait..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... unused) {
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(url); // getting XML from URL
return xml;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
XMLParser parser = new XMLParser();
Document doc = parser.getDomElement(result); // getting DOM element
NodeList nl = doc.getElementsByTagName("song");
// looping through all song nodes <song>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ARTIST, parser.getValue(e, KEY_ARTIST));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
// adding HashList to ArrayList
songsList.add(map);
}
list=(ListView)findViewById(R.id.list);
adapter= new WbAdapter(POSTS.this, songsList);
list.setAdapter(adapter);
}
}
}
XMLParser class :
package com.sta.map;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
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;
}
/**
* Getting XML DOM element
* #param XML string
* */
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 doc;
}
/** Getting node value
* #param elem element
*/
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 "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
EDIT 1: In the manifest I found this code :
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
I remove this part android:targetSdkVersion="16" and the parsing become very fast
Why ??
I found that on large files the performance of the XMLParser is very poor and very memory hungry. Specifically if one node in xml is very large, like an encoded bitmap. Think about it it has to load the entire string into memory at one time. I switched to parsing the file myself since I was only looking for one specific section and reading the data using a BufferedInputStream to avoid the memory spike.
This may not be your problem, but know that for very large files the XMLParser is not usable.
The problem is, when i try to get value from xml below
<item>
<title>The Return of Toastmasters</title>
<link>http://www.younginnovations.com.np/blogs/anjan/2012/06/return-toastmasters</link>
<description><p>As the title implies, it was the <strong>return of the Toastmasters</strong> at YoungInnovations on Thursday, May 24, 2012. I said "return" because Toastmasters saw a long gap of more than 3 months. Why the delay? Well, we shifted to a new office building and it took us some time to adjust properly into the new place. However, we're all glad that we continued with the event even after a long gap. And rightfully so, the MC for the day, Bimal Maharjan, announced the theme for the meeting: Return.</p>
<p><a href="http://www.younginnovations.com.np/blogs/anjan/2012/06/return-toastmasters" target="_blank">read more</a></p></description>
<comments>http://www.younginnovations.com.np/blogs/anjan/2012/06/return-toastmasters#comments</comments>
<category domain="http://www.younginnovations.com.np/category/tags/toastmasters">Toastmasters</category>
<pubDate>Mon, 04 Jun 2012 07:28:33 +0000</pubDate>
<dc:creator>anjan</dc:creator>
<guid isPermaLink="false">151 at http://www.younginnovations.com.np</guid>
</item>
and My application code below
News.java
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import android.app.ListActivity;
import android.content.Intent;
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 News extends ListActivity {
static final String URL = "http://www.younginnovations.com.np/blog/feed";
static final String KEY_ITEM = "item";
static final String KEY_TITLE = "title";
static final String KEY_DESC = "description";
static final String KEY_DATE = "pubDate";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.news);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL);
Document doc = parser.getDomElement(xml);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
for (int i = 0; i < nl.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
Log.e("Element", e.toString());
System.out.println(e);
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
menuItems.add(map);
}
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.news_list_item,
new String[] { KEY_TITLE, KEY_DESC, KEY_DATE }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
}
}
and XMLParse.java
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
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.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import android.util.Log;
public class XMLParser {
// constructor
public XMLParser() {
}
/**
* Getting XML from URL making HTTP request
* #param url string
* */
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;
}
/**
* Getting XML DOM element
* #param XML string
* */
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 doc;
}
/** Getting node value
* #param elem element
*/
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 "";
}
/**
* Getting node value
* #param Element node
* #param key string
* */
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
}
but while getting value of <description> tag.. there is HTML tags... So on "<" is returned as value.. in rest other its perfectly fine. How can i get all the value, or in best case how can i get values excluding HTML tags..
WAiting for help,
Thanks in advance
Thanks everyone for your support.. But i solved it in different way...
I did some changes in XMLParser.java file...
public final String getElementValue( Node elem ) {
Node child;
String returnValue = "" ;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
// String returnValue = child.getNodeValue();
returnValue += child.getTextContent();
}
}
// Log.e("ReturnValue", Html.fromHtml(returnValue).toString());
return Html.fromHtml(returnValue).toString();
}
}
return "";
}
But still i have a problem. If there is picture in xml, that is returned as "obj", which i dont want to see..