[Solved-4 Solutions] How to fix android.os.NetworkOnMainThreadException ?



Error Description:

  • Error while running an 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();
click below button to copy the code. By - android tutorial - team
  • And it shows the below error:
android.os.NetworkOnMainThreadException
click below button to copy the code. By - android tutorial - team

Solution 1:

  • 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();
            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
    }
}

click below button to copy the code. By - android tutorial - team

How to execute the task:

In MainActivity.java file we can add this line within the oncreate() method

new RetrieveFeedTask().execute(urlToRssFeed);
click below button to copy the code. By - android tutorial - team
  • Don't forget to add this to AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
click below button to copy the code. By - android tutorial - team

Solution 2 :

  • You should almost always run network operations on a thread or as an asynchronous task. But if you know better and are willing to accept the consequences, and must do network operations on the main thread, you can override the default behavior:

Add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy); 
click below button to copy the code. By - android tutorial - team
  • In your class, ADD this permission in android manifest.xml file:
<uses-permission android:name="android.permission.INTERNET"/>
click below button to copy the code. By - android tutorial - team

Consequences:

  • Your app will (in areas of spotty internet connection) become unresponsive and lock up, the user perceives slowness and has to do a force kill, and you risk the activity manager killing your app and telling the user that the app has stopped.
  • Android has some good tips on good programming practices to design for responsiveness.

Solution 3:

Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try  {
            //Your code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start(); 
click below button to copy the code. By - android tutorial - team

Solution 4 :

  • Do not use strictMode (only in debug mode)
  • Do not change SDK version
  • Do not use a separate thread

Use Service or AsyncTask


Related Searches to How to fix android.os.NetworkOnMainThreadException ?