How to Fix 'android.os.NetworkOnMainThreadException'? - GeeksforGeeks

23 Jun, 2021
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!
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!
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.
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);}
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();
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
// GeeksforGeeksprivate void gfg(){    fetchData();    // Add code which needs to     // be done in the background.}  @Background// This goes in the Backgroundprotected void fechData()}
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!
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Add Image to Drawable Folder in Android Studio?
How to Change the Background Color After Clicking the Button in Android?
How to Retrieve Data from the Firebase Realtime Database in Android?
GridView in Android with Example
ImageView in Android with Example