Parsing individual parts of an xml file from WebService - Android - java

I'm trying to parse the sunrise and sunset time from this webservice and display them into two separate textviews.
I've been trying to follow this tutorial but I'm struggling to understand how to adapt it:
http://www.androidhive.info/2011/11/android-xml-parsing-tutorial/
In that example the xml file has parent and child nodes and loops to collect them all, in my example I just want to grab two specific parameters and be able to display them.
This is the code I currently have, at the moment it calls the webservice and display the full xml file in an EditText. I need to work out how parse the individual values rather than all of it.
package com.authorwjf.http_get;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
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.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class Main extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.my_button).setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(false);
new LongRunningGetIO().execute();
}
private class LongRunningGetIO extends AsyncTask <Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity) throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n>0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n>0) out.append(new String(b, 0, n));
}
return out.toString();
}
#Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String finalURL = "http://www.earthtools.org/sun/52.77431872/-1.20639/4/12/99/0";
HttpGet httpGet = new HttpGet(finalURL);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results!=null) {
EditText et = (EditText)findViewById(R.id.my_edit);
et.setText(results);
}
Button b = (Button)findViewById(R.id.my_button);
b.setClickable(true);
}
}
}
I've been attempting to sort this for a while now and I'm about ready to give up, if anybody could help me out and show me some working code to grab the sunset and sunrise times that would be amazing.
Thanks for looking x

While it's not the "easiest" or "quickest" implementation for parsing XML code, I've always preferred to use the SAXParser utilities from Android.
A great tutorial to follow that breaks everything down step by step is from tutsplus.com

You need to use an XML DOM parser, because it is the easiest.
You should send your results text to the XML parser using DocumentBuilderFactory and then request various values such as sunset and sunrise from the parser.
I suggest following this tutorial: Android XML Parsing Tutorial – Using DOMParser
Sunrise Example (pseudo-code... very pseudo-code):
NodeList nodeList = doc.getElementsByTagName("Morning");
Node node = nodeList.get("sunrise");
String sunrise = node.getValue();

http://www.mkyong.com/java/how-to-read-xml-file-in-java-sax-parser/
http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
You can choose between Sax parser or w3c dom parser.
The above has tutorials on the same.
public class MainActivity extends Activity {
String lsunrise,sunset;
String xml= "<sun >"+
"<version>1.0</version>"+
"<location>"+
"<latitude>52.77431872</latitude>"+
"<longitude>-1.20639</longitude>"+
"</location>"+
"<date>"+
"<day>4</day>"+
"<month>12</month>"+
"<timezone>0</timezone>"+
"<dst>0</dst>"+
"</date>"+
"<morning>"+
"<sunrise>07:45:31</sunrise>"+
"<twilight>"+
"<civil>07:05:54</civil>"+
"<nautical>06:22:57</nautical>"+
"<astronomical>05:41:56</astronomical>"+
"</twilight>"+
"</morning>"+
"<evening>"+
"<sunset>16:02:28</sunset>"+
"<twilight>"+
"<civil>16:42:03</civil>"+
"<nautical>17:24:58</nautical>"+
"<astronomical>18:05:57</astronomical>"+
"</twilight>"+
"</evening>"+
"</sun>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parse();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
void parse()
{ try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
DefaultHandler handler = new DefaultHandler() {
boolean sr=false;
boolean ss=false;
public void startElement(String uri, String localName,String qName,
Attributes atts) throws SAXException {
//System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("sunrise")) {
sr=true;
}
if (qName.equalsIgnoreCase("sunset")) {
ss=true;
}
}
public void endElement(String uri, String localName,
String qName) throws SAXException {
//System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException
{
if (sr) {
System.out.println("FSun rise: " + new String(ch, start, length));
sr = false;
}
if (ss) {
System.out.println("Sun set : " + new String(ch, start, length));
ss = false;
}
}
};
saxParser.parse(is, handler);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Outputs snrise and sunset. Modify the above accordingly to get other tag values.

Edit: please see this related question. Parsing sunrise and sunset values from web service
You can parse the xml and set the values to the view.
Check out this tutorial.
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
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;
//here's your xml string.
String test = "<sun xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://www.earthtools.org/sun.xsd\"><version>1.0</version><location><latitude>52.77431872</latitude><longitude>-1.20639</longitude></location><date><day>4</day><month>12</month><timezone>0</timezone><dst>0</dst></date><morning><sunrise>07:45:31</sunrise><twilight><civil>07:05:54</civil><nautical>06:22:57</nautical><astronomical>05:41:56</astronomical></twilight></morning><evening><sunset>16:02:28</sunset><twilight><civil>16:42:03</civil><nautical>17:24:58</nautical><astronomical>18:05:57</astronomical></twilight></evening></sun>";
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
InputSource s = new InputSource(new StringReader(test));
Document doc = dBuilder.parse(s);
doc.getDocumentElement().normalize();
Log.v("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("morning");
Log.v("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("sunrise : " + eElement.getElementsByTagName("sunrise").item(0).getTextContent());
}
}
} catch (Exception e) {
e.printStackTrace();
}

Related

RSS Feed not populating textview

I'm trying to build a news reader app for a project that takes the BBC RSS feed and loads it into a textview. All my code seems to be correct but for some reason the textview doesn't populate and I have a sneaking suspicion, after debugging it, that it's caused by the app not implementing open stream. Code is below. Any idea what might be causing the issue?
package com.example.finalproject_newsapp;
import androidx.appcompat.app.AppCompatActivity;
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.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
String rss = "";
boolean item = false;
private class RSSHandler extends DefaultHandler {
public void startElement(String uri, String localName, String qName,
Attributes attrs) throws SAXException {
if (localName.equals("item"))
item = true;
if (!localName.equals("item") && item == true)
rss = rss + localName + ": ";
}
public void endElement(String namespaceURI, String localName,
String qName) throws SAXException {
}
public void characters(char[] ch, int start, int length)
throws SAXException {
String cdata = new String(ch, start, length);
if (item == true)
rss = rss + (cdata.trim()).replaceAll("\\s+", " ") + "\t";
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView feed = findViewById(R.id.BBC_feed);
try {
URL rssUrl = new URL("http://feeds.bbci.co.uk/news/world/us_and_canada/rss.xml");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
RSSHandler rssHandler = new RSSHandler();
xmlReader.setContentHandler(rssHandler);
InputSource inputSource = new InputSource(rssUrl.openStream());
xmlReader.parse(inputSource);
} catch (MalformedURLException | ParserConfigurationException | SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
feed.setText(rss);
}
}

Need to change format of date in my Android app

UPDATE. I'm really struggling with the answers given (they're not bad answers, I'm just struggling)
It would really help for more detailed answers
I'm pulling in an RSS feed into my app, the pubDate is currently showing up as for example Mon, 10 Nov 2014 03:34:38 +0000.
I need it to show up in a more user friendly manner. I've looked at all the options, SimpleDateFormat..etc, I'm sort of new to Java so all previous suggestions are just going over my head, I'm looking for what I actually need to put in my code.
Code is as follows
AndroidXMLParsingActivity.java
package com.example.myapp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Locale;
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.text.Html;
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;
import java.util.Calendar;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
public class AndroidXMLParsingActivity extends ListActivity {
// All static variables
static final String URL = "http://example.xml";
// XML node keys
static final String KEY_ITEM = "item"; // parent node
static final String KEY_DATE = "pubDate";
static final String KEY_DESC = "description";
static final String KEY_ID = "title";
static final String KEY_LDESC = "content:encoded";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
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, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
map.put(KEY_DATE, parser.getValue(e, KEY_DATE));
map.put(KEY_DESC, parser.getValue2(e, KEY_DESC));
map.put(KEY_LDESC, parser.getValue2(e, KEY_LDESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
new String[] { KEY_ID, KEY_LDESC, KEY_DATE}, new int[] {
R.id.name, R.id.content_encoded, R.id.pubDate });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
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 description = ((TextView) view.findViewById(R.id.description)).getText().toString();
String Ldescription = ((TextView) view.findViewById(R.id.content_encoded)).getText().toString();
String pubDate = ((TextView) view.findViewById(R.id.pubDate)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_ID, name);
in.putExtra(KEY_DESC, description);
in.putExtra(KEY_LDESC, Ldescription);
in.putExtra(KEY_DATE, pubDate);
startActivity(in);
}
});
}
}
XMLParser.java
package com.example.myapp;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
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.CharacterData;
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 "";
}
public final String getElementValue2( 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 ){
if(child.getNodeType() == Node.CDATA_SECTION_NODE){
return child.getNodeValue();
}
}
}
}
return "";
//return elem.getTextContent();
}
public static String getCharacterDataFromElement(Node elem) {
Node child = elem.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
public String getValue3(Element item, String str){
NodeList n = item.getElementsByTagNameNS("http://purl.org/rss/1.0/modules/content/", str);
String ses = this.getElementValue2(n.item(0));
//return this.getElementValue2(n.item(0));
//return ses;
String mim =ses.replaceAll("(?s)\\<.*?\\>", " \n");
//return Promjena(ses);
return mim;
}
/**
* 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));
}
public String getValue2(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLParser.getCharacterDataFromElement(n.item(0));
}
}
I'm not sure if you need any more information.
I'm also sure there is a lot of bad or redundant code, any help with that would be great!
Thank you very much!
String date = "Mon, 10 Nov 2014 03:34:38 +0000";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
Date _date = null;
try {
_date = sourceFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(_date .toString());
// print the Date in year month and date
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(targetFormat.format(_date));
You can you SimpleDateFormat class to convert friendly date as following
public String getFriendlyDayString(Date pubDate){
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(pubDate);
}
You can pass your pubDate to like this getFriendlyDateString(pubDate);
i tried replacing
String pubDate = ((TextView) view.findViewById(R.id.pubDate)).getText().toString();
with
String pubDate = "Mon, 10 Nov 2014 03:34:38 +0000";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
Date _date = null;
try {
_date = dateFormat.parse(pubDate);
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(_date .toString());
// print the Date in year month and date
SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
((TextView) view.findViewById(R.id.pubDate)).getText().toString();
didn't work...am I on the right track?

How can I parse xml file from url

I try to get currency from this url http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml. But my parsing doesn't work. This is my code.
http://www.ecb.europa.eu/stats/exchange/eurofxref/html/index.en.html
AndroidXMLParsingActivit.java
package com.androidhive.xmlparsing;
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.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 AndroidXMLParsingActivity extends ListActivity {
// All static variables
//static final String URL = "http://api.androidhive.info/pizza/?format=xml";
static final String URL = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml";
// XML node keys
//static final String KEY_ITEM = "item"; // parent node
static final String KEY_ITEM = "Cube"; // parent node
static final String KEY_ID = "currency";
static final String KEY_NAME = "rate";
/*static final String KEY_ID = "id";
static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
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, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID));
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
//map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
//map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
// adding HashList to ArrayList
menuItems.add(map);
}
// Adding menuItems to ListView
ListAdapter adapter = new SimpleAdapter(this, menuItems,
R.layout.list_item,
//new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
new String[] { KEY_NAME, KEY_ID, KEY_ID }, new int[] {
R.id.name, R.id.desciption, R.id.cost });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
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.cost)).getText().toString();
String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
in.putExtra(KEY_ID, cost);
in.putExtra(KEY_NAME, name);
//in.putExtra(KEY_COST, cost);
//in.putExtra(KEY_DESC, description);
startActivity(in);
}
});
}
}
SingleMenuItemActivity.java
package com.androidhive.xmlparsing;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class SingleMenuItemActivity extends Activity {
// XML node keys
static final String KEY_ID = "currency";
static final String KEY_NAME = "rate";
/*static final String KEY_NAME = "name";
static final String KEY_COST = "cost";
static final String KEY_DESC = "description";*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single_list_item);
// getting intent data
Intent in = getIntent();
// Get XML values from previous intent
String name = in.getStringExtra(KEY_NAME);
String cost = in.getStringExtra(KEY_ID);
/*String cost = in.getStringExtra(KEY_COST);
String description = in.getStringExtra(KEY_DESC);*/
// Displaying all values on the screen
TextView lblName = (TextView) findViewById(R.id.name_label);
TextView lblCost = (TextView) findViewById(R.id.cost_label);
TextView lblDesc = (TextView) findViewById(R.id.description_label);
lblName.setText(name);
lblCost.setText(cost);
lblDesc.setText(cost);
Log.i("name", name+"");
Log.i("cost", cost+"");
}
}
XMLParser.java
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.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));
}
}
Original post from here.
File fXmlFile = new File("your XML file");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("Cube");
System.out.println("----------------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
System.out.println("\nCurrent Element :" + nNode.getNodeName());
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String currency = eElement.getAttribute("currency");
String rate = eElement.getAttribute("rate");
if(currency.isEmpty()){
continue;
}
System.out.println("Ccurrency :" + currency);
System.out.println("Rate : " + rate);
}
}
It's printing the currency and the Rate.
Just replace
File fXmlFile = new File("your XML file");
on
URL url = null;
try {
url = new URL("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
URLConnection conn = null;
try {
conn = url.openConnection();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
And code must run in AsyncTask. I will send full source code through few days.

Facebook RSS Feed in Android app crashing

So I tried to set up an RSS feed for my Android application with the attached code, yet when I run it on the emulator, it crashes and I receive the attached errors in my LogCat. Any ideas for what could be wrong? Thanks in advance!!!
package com.fixed_gear_app;
import java.io.IOException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
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;
public class RSSFeed extends Activity {
/** Called when the activity is first created. */
String rssResult = "";
boolean item = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rssfeed);
TextView rss = (TextView) findViewById(R.id.rss);
try {
URL rssUrl = new URL("https://www.facebook.com/feeds/page.php?format=rss20&id=619608694724497");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
RSSHandler rssHandler = new RSSHandler();
xmlReader.setContentHandler(rssHandler);
InputSource inputSource = new InputSource(rssUrl.openStream());
xmlReader.parse(inputSource);
} catch (IOException e) {rss.setText(e.getMessage());
} catch (SAXException e) {rss.setText(e.getMessage());
} catch (ParserConfigurationException e) {rss.setText(e.getMessage());
}
rss.setText(rssResult);
}
/**public String removeSpaces(String s) {
StringTokenizer st = new StringTokenizer(s," ",false);
String t="";
while (st.hasMoreElements()) t += st.nextElement();
return t;
}*/
private class RSSHandler extends DefaultHandler {
public void startElement(String uri, String localName, String qName,
Attributes attrs) throws SAXException {
if (localName.equals("item"))
item = true;
if (!localName.equals("item") && item == true)
rssResult = rssResult + localName + ": ";
}
public void endElement(String namespaceURI, String localName,
String qName) throws SAXException {
}
public void characters(char[] ch, int start, int length)
throws SAXException {
String cdata = new String(ch, start, length);
if (item == true)
rssResult = rssResult +(cdata.trim()).replaceAll("\\s+", " ")+"\t";
}
}
}
You are attempting to do network communication on the main Activity thread. Android, by default, disallows this, (as you do not know how long it can take) so you will have to move your networking code to a class extending AsyncTask. Have a read of this, which shows you how to put it on an AsyncTask.

Parsing two elements with the same name - Pull Parser

My last question was badly phrased - I am attempting to parse the following xml:
I am having issues parsing the elements inside congestion location:
<tns:camera>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Eastbound</tns:direction>
<tns:order>6</tns:order>
</tns:congestionLocations>
<tns:congestionLocations>
<tns:congestion>Free Flow</tns:congestion>
<tns:direction>Westbound</tns:direction>
<tns:order>2</tns:order>
</tns:congestionLocations>
<tns:id>130</tns:id>
<tns:offline>false</tns:offline>
<tns:underMaintenance>false</tns:underMaintenance>
</tns:camera>
Using XMLPullParser, I can read the id, offline, etc elements. This works fine. I've written my code to parse the XML below:
// Get our factory and PullParser
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xpp = factory.newPullParser();
// Open up InputStream and Reader of our file.
FileInputStream fis = ctx.openFileInput("CameraSites.xml");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
// point the parser to our file.
xpp.setInput(reader);
// get initial eventType
int eventType = xpp.getEventType();
// Loop through pull events until we reach END_DOCUMENT
while (eventType != XmlPullParser.END_DOCUMENT) {
// Get the current tag
String tagname = xpp.getName();
// React to different event types appropriately
switch (eventType) {
case XmlPullParser.START_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// If we are starting a new <site> block we need
//a new CameraClass object to represent it
curCameraClass = new CameraClass();
}
break;
case XmlPullParser.TEXT:
//grab the current text so we can use it in END_TAG event
curText = xpp.getText();
break;
case XmlPullParser.END_TAG:
if (tagname.equalsIgnoreCase(KEY_SITE)) {
// if </site> then we are done with current Site
// add it to the list.
CameraSites.add(curCameraClass);
} else if (tagname.equalsIgnoreCase(KEY_ID)) {
curCameraClass.setID(curText);
} else if (tagname.equalsIgnoreCase(KEY_MAIN)) {
curCameraClass.setMAIN(curText);
}
break;
default:
break;
}
//move on to next iteration
eventType = xpp.next();
}
} catch (Exception e) {
e.printStackTrace();
}
// return the populated list.
return CameraSites;
}
My question is, how would I parse the congestion and direction elements found in the congestion locations? I am parsing these into a get/set method with a class (CameraClass).
Thanks in advance!
Here is the code with your xml..
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
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.SAXException;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class FileActivity extends Activity {
// Progress dialog
ProgressDialog pDialog;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file);
String data = "<tns:camera>"
+" <tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Eastbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:congestionLocations>"
+"<tns:congestion>Free Flow</tns:congestion>"
+"<tns:direction>Westbound</tns:direction>"
+"</tns:congestionLocations>"
+"<tns:description>Bond St looking east</tns:description>"
+"<tns:direction>Eastbound</tns:direction>"
+"<tns:group>SH16-North-Western</tns:group>"
+"<tns:lat>-36.869</tns:lat>"
+"<tns:lon>174.746</tns:lon>"
+"<tns:name>SH16 1 Bond St</tns:name>"
+"<tns:viewUrl>http://www.trafficnz.info/camera/view/130</tns:viewUrl>"
+" </tns:camera>";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
new XmlParsing(data).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
else
new XmlParsing(data).execute(new String[]{null});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class XmlParsing extends AsyncTask<String, Void, String> {
// variables passed in:
String data;
// constructor
public XmlParsing(String data) {
this.data = data;
}
#Override
protected void onPreExecute() {
pDialog = ProgressDialog.show(FileActivity.this, "Fetching Details..", "Please wait...", true);
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder= dbFactory.newDocumentBuilder();
FileOutputStream out = openFileOutput("hello.txt",Context.MODE_PRIVATE);
out.write(data.getBytes());
out.close();
BufferedReader input = new BufferedReader(new InputStreamReader(openFileInput("hello.txt")));
StringBuffer inLine = new StringBuffer();
String text;
while ((text = input.readLine()) != null) {
inLine.append(text);
inLine.append("\n");
}
input.close();
String finalData =inLine.toString();
InputStream is = new ByteArrayInputStream(finalData.getBytes("UTF-8"));
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("tns:camera");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("tns:group");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Log.v("tns:group : "+((Node) nameList.item(0)).getNodeValue());
Element fstElmnt1 = (Element) node;
NodeList nameList1 = fstElmnt1.getElementsByTagName("tns:viewUrl");
Element nameElement1 = (Element) nameList1.item(0);
nameList1 = nameElement1.getChildNodes();
Log.v("tns:viewUrl : "+ ((Node) nameList1.item(0)).getNodeValue());
if(node.getNodeType() == Node.ELEMENT_NODE)
{
Element e = (Element) node;
NodeList resultNodeList = e.getElementsByTagName("tns:congestionLocations");
int resultNodeListSize = resultNodeList.getLength();
for(int j = 0 ; j < resultNodeListSize ; j++ )
{
Node resultNode = resultNodeList.item(j);
if(resultNode.getNodeType() == Node.ELEMENT_NODE)
{
Element fstElmnt2 = (Element) resultNode;
NodeList nameList2 = fstElmnt2.getElementsByTagName("tns:congestion");
Element nameElement2 = (Element) nameList2.item(0);
nameList2 = nameElement2.getChildNodes();
Log.v("tns:congestion", ""+((Node) nameList2.item(0)).getNodeValue());
Element fstElmnt3 = (Element) resultNode;
NodeList nameList3 = fstElmnt3.getElementsByTagName("tns:direction");
Element nameElement3 = (Element) nameList3.item(0);
nameList3 = nameElement3.getChildNodes();
Log.v("tns:direction--", ""+((Node) nameList3.item(0)).getNodeValue());
}
}
}
}
} 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();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// Now we have your JSONObject, play around with it.
if (pDialog.isShowing())
pDialog.dismiss();
}
}
}
From log you can see the result...

Categories

Resources