Open In App

How to Fix “android.os.Network On Main Thread Exception error” in Android Studio?

Last Updated : 05 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The main reason for Network On Main Thread Exception Error is because the newer versions of android are very strict against the UI thread abuse. Whenever we open an app, a new “main” thread is created which helps applications interact with the running components of an app’s UI and is responsible for dispatching events to assigned widgets. The entire User Interface is blocked when time-consuming actions are performed on the UI thread.

When an app attempts to perform networking operations on the main thread a Network  On Main Thread Exception Error is thrown. The error shows on all applications targeting Honeycomb SDK or higher. Applications get disabled to download files, connect to remote MySQL database, perform HTTP requests or establish a socket connection.

Solutions

The solution is to completely wrap any task that attempts to perform actions like download files, connect to remote MySQL database, perform HTTP requests or establish a socket connection into a separate async function. A new thread is created by the async function, and hence, these processes do not run on the UI thread. We can also override the instruction, but in this situation, the task manager may have to kill the application and it will make the application unresponsive.

Solution 1

To overcome this situation, add the following to the class where the user is performing network operations:

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

Add the following permissions to the manifest.xml file:

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

Solution 2

To solve this problem we will use  a new Thread

Example:

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

thread.start(); 

Solution 3

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

Solution 4

When an app attempts to perform networking operations on the main thread a Network  On Main Thread Exception Error is thrown.

Example:

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

Solution 5

For the execution of the task in the MainActivity.java file, We will add this line within the onCreate() method 

new RetrieveFeedTask().execute(urlToRssFeed); 

and do not forget to add this to the AndroidManifest.xml file: 

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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads