Open In App

How to Fix ‘android.os.NetworkOnMainThreadException’?

Last Updated : 13 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

While working on some serious project in Android Studio you might’ve happened to come across this nasty error in the above line and all the worlds tried to tear apart. Well, this article has the perfect solution on how to get rid of that ‘android.os.NetworkOnMainThreadException’ error! Read to fix it!

Method #1: The Async Task Way

Believe it or not but when a program tries to perform a networking activity on its main thread, this exception is thrown. Use AsyncTask to run your code. After adopting the async task you could call up the below method to run your task.

Java




new RetriveDSAConcepts().execute(GeeksforGeeks);


GeekTip: Don’t forget to add:
<uses-permission android:name=”android.permission.INTERNET”/>
in your projects manifest file!

Method #2: Overriding the Default Methods

Almost all network actions should be performed in a thread or as an asynchronous task. However, if you are willing to face the penalties, you can remove this restriction and override the default behavior.

Java




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


Consequences:

Your app will become unresponsive and lock up (in locations with patchy internet connection), the user will sense slowness and will have to forcibly quit the program, and you risk the activity management deleting your app and informing the user that it has stopped.

Method #3: Disabling Strict Mode

We all know what Strict Mode in Android is, and if you are unable to achieve your task, then you can try disabling the Strict Mode in your application. To bypass it, simply go ahead and add this to your NetworkActivity.java.

Java




if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy gfgPolicy =
        new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(gfgPolicy);
}


Method #4: Changing the Worker Thread Manually

If the above methods don’t work out for you, you can manually change the network task to a side thread, and then wait for the result then include it in the main thread, so that the user doesn’t feel sluggish. Add the code below to your NetworkActivity.java file to change the thread.

Reference Article: How Does Threading Work in Android?

Java




Thread gfgThread = new Thread(new Runnable() {
    @Override
    public void run() {
        try  {
            // Your network activity
           // code comes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});
 
gfgThread.start();


Method #5: Using Android Annotations

You can also use the Android Annotations to fix this error and get back going, just add the below code to your Java file and see things move!

Java




// GeeksforGeeks
private void gfg()
{
    fetchData();
    // Add code which needs to
    // be done in the background.
}
 
@Background
// This goes in the Background
protected void fetchData()
}


And just like adding these simple code snippets could help you get rid of that error forever, and you’re back working on that important project once again!



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads