How to parse a url in an android application - android

I want to parse the URL of a weather API in my sample Android app, but it arises an exception while parsing the url.
If I comment the last statement of the try block:
xr.parse(new InputSource(url.openStream()));
then my program runs successfully. Please revise my code where I parse my URL.
try {
URL url;
String queryString ="http://free.worldweatheronline.com/feed/weather.ashx?q=34.01,71.54&format=xml&num_of_days=5&key=ccad66928f081759132201";
url = new URL(queryString.replace(" ", "%20"));
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
WeatherHandler myWeatherHandler = new WeatherHandler();
xr.setContentHandler(myWeatherHandler);
xr.parse(new InputSource(url.openStream()));
Log.d(TAG, "it's all right");
} catch (Exception e) {
System.out.println(e);
Log.d(TAG, "it's Wrong");
}
Here is the Screen shot of the log cat when the exception occurs.

Are you sure the line:
new InputSource(url.openStream());
from
xr.parse(new InputSource(url.openStream()));
is returning something? If you have to connect to the Internet, don't forget to add the permissions to the manifest. And you should also test if you actually get something from that url before trying to parse.
At least that's my interpretation from your Log and Exception.

Related

url connection gives FileNotFoundException

I'm doing an application that reads a xml from a url and displays it on screen, but when I want to read the answer gives me a FileNotFoundException
this is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView rss = (ListView) findViewById(R.id.list);
try {
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("acceso!a!backend", "nu3v0!1nf0b43!2013".toCharArray());
}
});
URL rssUrl = new URL("http://ec2-54-224-94-185.compute-1.amazonaws.com/adjuntos/162/rss/home_mobile.xmlx");
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
RSSHandler rssHandler = new RSSHandler();
xmlReader.setContentHandler(rssHandler);
////////here I am getting the FileNotFoundException
InputSource inputSource = new InputSource(rssUrl.openStream());
xmlReader.parse(inputSource);
NoticiasAdapter na = new NoticiasAdapter(this ,rssHandler.getChannel());
rss.setAdapter(na);
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
}
It's likely that URL does not exist, then. :)
Have you tried visiting that URL in your browser to confirm that it exists?
Also, the URLConnection throws the IOException when you start doing I/O because that's when it tries to make the physical connection. If you want the system to make the connection earlier (to make sure the URL exists, for example), you can use URLConnection's connect() method to make it connect earlier. (Just make sure you've done necessary connection configuration -0setting headers, etc. -- beforehand!) There's nothing wrong with waiting until you do I/O to make the connection, so you don't need to call connect() to make the connection earlier, but you can make the connection earlier if you want to.
I tried to open that url and it gives me a 404 error not found.
It seems likely the URL does not exist.
You could modify rssUrl.openStream() into two lines
URLConnection connection = rssUrl.openConnection()
InputSource inputSource = new InputSource(connection.getInputStream())
This way you could debug to figure out if you are able to connect instead of doing it all in one step. After all openStream() is shorthand for openConnection().getInputStream() http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#openStream()
Once you figure out you have a valid URL and are able to connect you can change back to your implementation if desired.

Issue with SAXparser

I've implemented a SAXparser in my application which has worked fine previously but i'm having problems with a new XML document.
This is my parser
public List<Article> getLatestArticles(String feedUrl) {
URL url = null;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
xr.setContentHandler(this);
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString());
} catch (SAXException e) {
Log.e("RSS Handler SAX", e.toString());
} catch (ParserConfigurationException e) {
Log.e("RSS Handler Parser Config", e.toString());
}
catch (java.lang.IllegalArgumentException e){
Log.e("RSS Handler lang", e.getMessage() + " >> " + e.toString());
}
return articleList;
}
The parser starts off ok but then i get a java.lang.IllegalArgumentException error. I believe this may be due to an element with no value in my xml feed, it looks like this <Description/>.
Any suggestion on how to fix this would be much appreciated.
If </Description> is a self closing tag (i.e. it has not opening <Description> tag and no text value) then this syntax is perfectly correct.
It is hard to tell exactly what is causing the error without seeing the callback methods (e.g. startElement method) but there is one major gottcha that you can check
The SAX parse method throws an illegalArguementException if the InputStream is null. It might be worth checking the value coming into the SAX parser.
You can use the following code to check the input stream for nulls.
InputStreamReader reader = new InputStreamReader(url.openStream());
if (!reader.ready()) {
System.out.println("error");
}
The connection could close before all the data downloads.
Try using a BufferedInputStream and see if that helps:
BufferedInputStream _url_ = new BufferedInputStream(new URL(feedUrl).openStream());
...
BufferedReader isr = new BufferedReader(new InputStreamReader(_url_));
InputSource is = new InputSource(isr);
xr.parse(is);
<Description/> is the xml construction issue for SAXParser. have a look into the structure.
Ideally it should be </Description> as a closing tag.
For self-closing tags SAXParser will assume it as a closing tag.
So instead of startElement you will get a call from endElement.

Accessing BBC RSS feed on Android App

I'm having some trouble reading two BBC feeds on my Android app, they both seem to time out. This is especially strange because all other feeds work fine using the exact same system. I guess if someone could test them in their Eclipse it might help me determine if my work's firewall/proxy is restricting access to this specific website.
The feeds are http://newsrss.bbc.co.uk/weather/forecast/2159/Next3DaysRSS.xml and http://feeds.bbci.co.uk/news/england/kent/rss.xml.
I have other feeds being read with work fine e.g. http://www.kent.ac.uk/news/rss.html
The other strange thing is the chap next to me working on an iPhone under the same network restrictions is not having a problem.
Any help would be greatly appreciated!
For info here is the code I've been using to pull in feeds:
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
// proxy settings
String proxyHost = android.net.Proxy.getDefaultHost();
int proxyPort = android.net.Proxy.getDefaultPort();
if(proxyPort != -1){
params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost,proxyPort));
}
URL url = null;
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
url = new URL(feedUrl);
URLConnection conn = url.openConnection();
// setting these timeouts ensures the client does not deadlock indefinitely
// when the server has problems.
conn.setConnectTimeout(2000);
conn.setReadTimeout(2000);
xr.setContentHandler(this);
/* This is where it lurches indefinitely VVV */
xr.parse(new InputSource(url.openStream()));
} catch (IOException e) {
Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString());
} catch (SAXException e) {
Log.e("RSS Handler SAX", e.toString());
} catch (ParserConfigurationException e) {
Log.e("RSS Handler Parser Config", e.toString());
}
I'm going to guess you're having the same problem as this question. Does it work if you take out the proxy settings? If that's the problem, I'd suggest writing the response stream to memory before feeding it to your XMLReader.

read with SAxParser

hi everyone I try to read the information of this direction
http://finance.yahoo.com/d/quotes.csv?s=XOM+BBDb.TO+JNJ+MSFT&f=snd1l1yr
SAXParserFactory factory= SAXParserFactory.newInstance();
try {
SAXParser parser= factory.newSAXParser();
RssHandler handler= new RssHandler();
parser.parse(this.getInputStream(), handler);
return handler.getQuotes();
} catch (Exception e) {
throw new RuntimeException(e);
}
but I have this error
not well-formed (invalid token)
if I put this direction http://finance.yahoo.com/rss/headline?s=yhoo the application works well, but I need read the other direction.
any idea!!!
thanks in advance.
The first URL contains something like this:
"XOM","Exxon Mobil Corpo","6/1/2011",82.03,2.14,11.89
"BBD-B.TO","BOMBARDIER INC., ","6/1/2011",6.95,1.11,16.07
"JNJ","Johnson & Johnson","6/1/2011",66.48,3.25,15.26
"MSFT","Microsoft Corpora","6/1/2011",24.43,2.44,9.94
which is CSV (comma-separated values) formatted data.
CSV is not a valid RSS feed format. It's not even XML.

do not understand xml parsing code

the following code is for xml parsing.
try
{
HttpEntity entity = response.getEntity();
final InputStream in = entity.getContent();
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
final XmlHandler handler = new XmlHandler();
Reader reader = new InputStreamReader(in, "UTF-8");
InputSource is = new InputSource(reader);
is.setEncoding("UTF-8");
parser.parse(is, handler);
//TODO: get the data from your handler
}
catch (final Exception e)
{
Log.e("ParseError", "Error parsing xml", e);
}
over here where do i pass the url.
also the response object in the line
response.getEntity() is an object of HttpResponse()?
thank you in advance.
The code you show is the processing after the url connection has been opened, and the result has been obtained. At this point there is no more url to pass.
response is the HttpResponse.
I think you can do something like this:
Url url = new URL("http:// [and so on]");
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(url.openStream()));

Categories

Resources