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();
To run this code
android.os.NetworkOnMainThreadException I get this error. How should I fix it?
android thread-exception
Android.os.NetworkOnMainThreadException This error occurs when an application attempts a network operation on the main thread. Using AsyncTask
class RetrieveFeedTask 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
}
}
Do it like this. Execute new RetrieveFeedTask().execute(urlToRssFeed);
This is how you do it.
And at Android Manifest, <uses-permission android:name="android.permission.INTERNET"/>
Please make sure to do it.
© 2024 OneMinuteCode. All rights reserved.