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.
Related
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);
}
}
XMLHandler.java
package com.example.listapps;
import java.text.AttributedCharacterIterator.Attribute;
import java.util.ArrayList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class XMLHandler extends DefaultHandler {
String PermissionList = "";
String Result = "";
public String getResult() {
return Result;
}
String[]Mypermission = {".READ_SMS",".SMS_SEND",".RECEIVE_SMS",".WRITE_SMS",".PROCESS_OUTGOING_CA","LL.MOUNT_UNMOUNT_FILESYSTEMS",".READ_HISTORY_BOOKMARKS",".WRITE_HISTORY_BOOKMARKS",".READ_LOGS",".INSTALL_PACKAGES",".MODIFY_PHONE_STATE"};
public void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {
if (qName.equals("uses-permission"))
{
PermissionList += attributes.getValue("name")+ " ";
int MaliciousPer =0;
String []permissions = PermissionList.split(" ");
for(int i=0; i<Mypermission.length; i++)
{
for(int j=0; j<permissions.length; j++)
{
if(Mypermission[i].equals(permissions[j].substring(permissions[j].lastIndexOf("."))))
{ MaliciousPer++; }
}
}
int PerCount = permissions.length;
if( PerCount == 9 && MaliciousPer == 0){result = "Yes";}
else{Result = "No";}
}
}
XMLParser.java
package com.example.listapps;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.content.Context;
import android.os.Environment;
import android.widget.Toast;
public class XMLParser extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.xml_parser)// show String Result on layout
parseXML();
}
public void parseXML() {
try {
String PkgName = PackageName;// PackageName want to pass from MainAciviy
String input = PkgName + ".xml";
InputSource inputSource = null;
String filename = Environment.getExternalStorageDirectory().getPath()+File.separator +"Tools" + File.separator + input;
FileInputStream xmlFileInputStream = new FileInputStream(filename);
inputSource = new InputSource(xmlFileInputStream);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
XMLHandler myXMLHandler = new XMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(inputSource);
String Result = myXMLHandler.getResult();
Toast.makeText(getBaseContext(), Result , Toast.LENGTH_LONG).show();
((Closeable) inputSource).close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
MainActivity.java
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListView;
public class MainActivity extends ListActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
new LoadApplications().execute();
}
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
ApplicationInfo app = applist.get(position);
String PackageName = app.packageName;
Intent intent = new Intent(getApplicationContext(), XMLParser.class);
intent.putExtra("PkgName", PackageName);//It is correct to pass value?
startActivity(intent);
}
}
When I click on lists, I want to pass String PackageName to PkgName under parseXML() and run XMLParser class as a new activity. And I want to show Result "Yes" or "No" on new activity's layout. Please fixed this code for me. Thank you for your answer.
I see you're passing the PackageName value to the XMLParser through the intent:
intent.putExtra("PkgName", PackageName);
To access this value in the XMLParser activity, just change this line:
String PkgName = PackageName;
To:
String PkgName = getIntent().getStringExtra("PkgName");
I keep getting this problem
Exception: Connection timeout
I am running my project on another device so i have to use the IP adress. So i change localhost:8080/lab/lab1.xml to http://192.168.1.5/lab/lab1.xml
Now after i run and it load for a while on the device after loading it then displays a
blank page. and when i checked Logcat it displays Exception: Connection timeout
Help me please. Thanks
So here is the MainActivity.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tvResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResponse = (TextView) findViewById(R.id.tvResponse);
new PostAsync().execute();
}
class PostAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
XMLHelper helper;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "by Es", "Loading", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for(EventValue event : helper.events) {
builder.append("\nWhat: " + event.getWhat());
builder.append("\nWhen: " + event.getWhen());
builder.append("\nWhere: " + event.getWhere());
builder.append("\n");
}
tvResponse.setText(builder.toString());
pd.dismiss();
}
}
}
Here is the XMLHelper.java
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHelper extends DefaultHandler {
/**
* The URL to be parsed
*/
private String URL_MAIN = "http://192.168.1.5/lab/lab1.xml";
String TAG = "XMLHelper";
Boolean currTag = false;
String currTagVal = "";
public EventValue event = null;
public ArrayList<EventValue> events = new ArrayList<EventValue>();
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser mSaxParser = factory.newSAXParser();
XMLReader mXmlReader = mSaxParser.getXMLReader();
mXmlReader.setContentHandler(this);
InputStream mInputStream = new URL(URL_MAIN).openStream();
mXmlReader.parse(new InputSource(mInputStream));
} catch(Exception e) {
// Exceptions can be handled for different types
// But, this is about XML Parsing not about Exception Handling
Log.e(TAG, "Exception: " + e.getMessage());
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currTag = false;
if(localName.equalsIgnoreCase("what"))
event.setWhat(currTagVal);
else if(localName.equalsIgnoreCase("when"))
event.setWhen(currTagVal);
else if(localName.equalsIgnoreCase("where"))
event.setWhere(currTagVal);
else if(localName.equalsIgnoreCase("event"))
events.add(event);
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i(TAG, "TAG: " + localName);
currTag = true;
currTagVal = "";
if(localName.equals("event"))
event = new EventValue();
}
}
Here is the EventValue.java
public class EventValue {
String what, when, where;
public String getWhat() {
return what;
}
public void setWhat(String what) {
this.what = what;
}
public String getWhen() {
return when;
}
public void setWhen(String when) {
this.when = when;
}
public String getWhere() {
return where;
}
public void setWhere(String where) {
this.where = where;
}
}
Here is the xml file lab1.xml (localhost:8080/lab/lab1.xml)
<event>
<what>Summer</what>
<when>March1</when>
<where>--</where>
</event>
<event>
<what>asdasdas</what>
<when>March 2</when>
<where>asasas</where>
</event>
<event>
<what>asdasdq</what>
<when>asdasdx</when>
<where>asdasdf</where>
</event>
If you are using port 8080 then you should use that in the connection url:
http://192.168.1.5:8080/lab/lab1.xml
It would also be a good idea to check that you can access the url with a browser from another machine.
My app starts.. loads.. and when it is done loading it displays only a blank page. It doesnt crash just display a blank page.
And I noticed at the logcat there is this error: Exception localhost/127.0.0.1:8080 Connection Refused
I am playing my app on another device not in an emulator.
So i am thinking it has an error on the url "localhost:8080/lab/lab1.xml"
OR it has an error on my codes.
So here is the MainActivity.java
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView tvResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvResponse = (TextView) findViewById(R.id.tvResponse);
new PostAsync().execute();
}
class PostAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
XMLHelper helper;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(MainActivity.this, "by Es", "Loading", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for(EventValue event : helper.events) {
builder.append("\nWhat: " + event.getWhat());
builder.append("\nWhen: " + event.getWhen());
builder.append("\nWhere: " + event.getWhere());
builder.append("\n");
}
tvResponse.setText(builder.toString());
pd.dismiss();
}
}
}
Here is the XMLHelper.java
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import android.util.Log;
public class XMLHelper extends DefaultHandler {
/**
* The URL to be parsed
*/
private String URL_MAIN = "http://localhost:8080/lab/lab1.xml";
String TAG = "XMLHelper";
Boolean currTag = false;
String currTagVal = "";
public EventValue event = null;
public ArrayList<EventValue> events = new ArrayList<EventValue>();
public void get() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser mSaxParser = factory.newSAXParser();
XMLReader mXmlReader = mSaxParser.getXMLReader();
mXmlReader.setContentHandler(this);
InputStream mInputStream = new URL(URL_MAIN).openStream();
mXmlReader.parse(new InputSource(mInputStream));
} catch(Exception e) {
// Exceptions can be handled for different types
// But, this is about XML Parsing not about Exception Handling
Log.e(TAG, "Exception: " + e.getMessage());
}
}
#Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if(currTag) {
currTagVal = currTagVal + new String(ch, start, length);
currTag = false;
}
}
#Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currTag = false;
if(localName.equalsIgnoreCase("what"))
event.setWhat(currTagVal);
else if(localName.equalsIgnoreCase("when"))
event.setWhen(currTagVal);
else if(localName.equalsIgnoreCase("where"))
event.setWhere(currTagVal);
else if(localName.equalsIgnoreCase("event"))
events.add(event);
}
#Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
Log.i(TAG, "TAG: " + localName);
currTag = true;
currTagVal = "";
if(localName.equals("event"))
event = new EventValue();
}
}
Here is the EventValue.java
public class EventValue {
String what, when, where;
public String getWhat() {
return what;
}
public void setWhat(String what) {
this.what = what;
}
public String getWhen() {
return when;
}
public void setWhen(String when) {
this.when = when;
}
public String getWhere() {
return where;
}
public void setWhere(String where) {
this.where = where;
}
}
Here is the xml file lab1.xml (localhost:8080/lab/lab1.xml)
<?xml version="1.0" encoding="utf-8"?>
<events>
<event>
<what>Summer</what>
<when>March1</when>
<where>--</where>
</event>
<event>
<what>asdasdas</what>
<when>March 2</when>
<where>asasas</where>
</event>
<event>
<what>asdasdq</what>
<when>asdasdx</when>
<where>asdasdf</where>
</event>
</events>
Please take a look at the codes. Thanks
EDIT-
it works now i am using computer IP adress but now the problem there is this new exception
Exception:Connection Timeout
Your error doesn't have anything to do with XML parsing. You have connection error. You are using localhost, which is the phone itself, of course it returns connection error. You probably meant your machine where you develop.
If you want to refer to the computer which is running the Android simulator, use the IP address 10.0.2.2 instead. You can read more from here.
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();
}