[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 - sql tutorial - team

Error:

android.os.NetworkOnMainThreadException
click below button to copy the code. By - sql tutorial - team
 threadexception

Learn sql - sql tutorial - threadexception - sql examples - sql programs

Solution 1:

This exception is thrown when an application attempts to perform a networking operation on its main thread. Run the 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 - sql tutorial - team

How to execute the task:

In MainActivity.java file we can add this line within the oncreate() method new RetrieveFeedTask().execute(urlToRssFeed); Don't forget to add this to AndroidManifest.xml file: <uses-permission android:name="android.permission.INTERNET"/>

Solution 2:

We should almost always run network operations on a thread or as an asynchronous task. But if we know better and are willing to accept the consequences, and must do network operations on the main thread, we 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 - sql tutorial - team

In the class,

and

ADD this permission in android manifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
click below button to copy the code. By - sql tutorial - team

Consequences:

The 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.

Solution 3:

We can solve this problem using a new Thread

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 - sql tutorial - team

Solution 4:

  1. Do not use strictMode (only in debug mode)
  2. Do not change SDK version
  3. Do not use a separate thread

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