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?
Use Service or AsyncTask
See also Stack Overflow question:
android.os.NetworkOnMainThreadException sending an email from Android
The top answer of spektom works perfect.
If you are writing the
AsyncTask
inline and not extending as a class, and on top of this, if there is a need to get a response out of theAsyncTask
, one can use theget()
method as below.(From his example.)
Although above there is a huge solution pool, no one mentioned
com.koushikdutta.ion
: https://github.com/koush/ionIt's also asynchronous and very simple to use:
Do the network actions on another thread
And add this to AndroidManifest.xml
You disable the strict mode using following code:
This is not recommended: use the
AsyncTask
interface.Full code for both the methods
I solved this problem using a new
Thread
.