Categories
android android-networking java networkonmainthread

How can I fix ‘android.os.NetworkOnMainThreadException’?

2646

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?

4

  • 138

    Read this blog post on the NetworkOnMainThreadException for more information. It explains why this occurs on Android 3.0 and above.

    Aug 7, 2012 at 12:38

  • 6

    To be on rite track first read about the Network Requests in android then i would recommend to study “Volley”.

    Jan 23, 2014 at 6:39

  • 3

    There are many alternative libraries that solve this issue. Many are listed at the bottom of this page. If you got more, we take them 🙂

    – Snicolas

    Feb 11, 2014 at 22:55

  • “Due to a bug in previous versions of Android, the system did not flag writing to a TCP socket on the main thread as a strict-mode violation. Android 7.0 fixes this bug. Apps that exhibit this behavior now throw an android.os.NetworkOnMainThreadException.” – So some of us haven’t hit this until recently! developer.android.com/about/versions/nougat/…

    – Jay

    Nov 19, 2017 at 22:51

2654

NOTE : AsyncTask was deprecated in API level 30.
AsyncTask | Android Developers

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;
        } 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:

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

3

  • So this running network operations on main thread is only problematic in android not in standard java code(code written in java but not for android application).??

    – y_159

    Jun 14, 2021 at 3:18

  • This is a good solution and it saved my time!

    Nov 16, 2021 at 12:43

  • 5

    Since AsyncTask is deprecated, what is the uptodate solution?

    Apr 5 at 7:01

753

You should almost always run network operations on a thread or as an asynchronous task.

But it is possible to remove this restriction and you override the default behavior, if you are willing to accept the consequences.

Add:

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

StrictMode.setThreadPolicy(policy);

In your class,

and

Add this permission in the Android manifest.xml file:

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

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:
NetworkOnMainThreadException | Android Developers

1

  • 1

    Wow thanks for that explanation I now understand. I saw an app and it had implemented that ThreadPolicy in its java classes I was abit confused what it was doing. When network was low I was seeing the Consequence which you’re talking about.

    – MosesK

    Jun 3, 2021 at 9:30

498

I solved 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(); 

3

  • How woulod you pass paramaters to this?

    – Haisi

    Jun 3, 2021 at 7:42

  • If you need to access the UI after the request, you need to return to the main thread at the end as explained here.

    Aug 9, 2021 at 10:43

  • simple and it works, thank you very much 🙂

    Mar 30 at 0:49