Wednesday 27 December 2017

java - How to fix 'android.os.NetworkOnMainThreadException'?

itemprop="text">

I got an error while running my
Android project for RssReader.



Code:



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
it shows the below
error:



android.os.NetworkOnMainThreadException


How
can I fix this issue?


itemprop="text">
class="normal">Answer



This
exception is thrown when an application attempts to perform a networking operation on
its main thread. Run your code in href="http://developer.android.com/reference/android/os/AsyncTask.html"
rel="noreferrer">AsyncTask:



class
RetrieveFeedTask extends AsyncTask {


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;
} finally {
is.close();
}

}

protected void onPostExecute(RSSFeed feed) {
// TODO:
check this.exception
// TODO: do something with the feed

}
}


How to
execute the task:



In
MainActivity.java file you can add this line within your
oncreate()
method



new
RetrieveFeedTask().execute(urlToRssFeed);


Don't
forget to add this to AndroidManifest.xml
file:



            android:name="android.permission.INTERNET"/>


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...