Home > DeveloperSection > Forums > What is android.os.NetworkOnMainThreadException
Samuel Fernandes
Samuel Fernandes

Total Post:154

Posted on    April-23-2015 5:22 AM

 Android Android  Thread  Exception 

 1 Reply(s)
 613  View(s)
Rate this:
In the below code I got an error when running my Android project for RssReader.

And it shows an error:

How can I fix this issue?

URL url = new URL(urlToRssFeed);
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader xmlreader = parser.getXMLReader();
RssHandler theRSSHandler = new RssHandler();
InputSource is = new InputSource(url.openStream());
return theRSSHandler.getFeed();

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    April-23-2015 7:39 AM

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in 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();
            InputSource is=new InputSource(url.openStream());
            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: 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:

<uses-permission android:name="android.permission.INTERNET"/>

Don't want to miss updates? Please click the below button!

Follow MindStick