In the below code I got an error when running my android project for RssReader.
URL url= new URL(urlToRssFeed);
SAXParserFactory factory =SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
XMLReader xmlreader=parser.getXMLReader();
RssHandler theRSSHandler=new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is=new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
and shows an error
android.os.NetworkOnMainThreadException
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in
AsyncTask
:class RetreiveFeedTask extends AsyncTask<String, Void, RSSFeed> {
private Exception exception;
protected RSSFeed doInBackground(String... urls) {
try {
URL url= new URL(urls[0]);
SAXParserFactory factory =SAXParserFactory.newInstance();
SAXParser parser=factory.newSAXParser();
XMLReader xmlreader=parser.getXMLReader();
RssHandler theRSSHandler=new RssHandler();
xmlreader.setContentHandler(theRSSHandler);
InputSource is=new InputSource(url.openStream());
xmlreader.parse(is);
return theRSSHandler.getFeed();
} catch (Exception e) {
this.exception = e;
return null;
}
}
protected void onPostExecute(RSSFeed feed) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
How to execute the task:
new RetreiveFeedTask().execute(urlToRssFeed);
Don't forget to add this to
<uses-permission android:name="android.permission.INTERNET"/> AndroidManifest.xml
file:
0 comments:
Post a Comment