How to Fix ‘android.os.NetworkOnMainThreadException’?

When working on an important project in Android Studio, you may receive the "android.os.NetworkOnMainThreadException" problem, which can be extremely frustrating. This post presents an excellent answer to this problem. Continue reading to learn how to solve it successfully!



Method #1: The Async task

When a program tries to perform a networking activity on its thread this exception is thrown. Async task you could call up the below to run your task.

 new  RetriveDSAConcepts().execute(testobject);

Method #2 : overriding the default methods.

Network actions should be performed in a thread or an asyc . if you are willing to face the penalties. Override the default  method.

 StrictMode.ThreadPolicy gfgPolicy = new   

 StrictMode.ThreadPolicy.Builder().permitAll().build();

 StrictMode.setThreadPolicy(gfgPolicy);

Method #3: overriding the default methods.

If you are unable to achieve your task then can try disabling the strict mode in your application.

 if (android.os.Build.VERSION.SDK_INT > 9) {

    StrictMode.ThreadPolicy gfgPolicy =

    new StrictMode.ThreadPolicy.Builder()

    .permitAll().build();

    StrictMode.setThreadPolicy(gfgPolicy);

 }


Method #4: overriding the default methods.

If none of the above mentioned techniques work for you, you can manually move the network operation to a side thread, wait for the outcome, and then merge it into the main thread to prevent user sluggishness. To switch the thread, add the following code to your NetworkActivity.java file.

  Thread demoThread = new Thread(new Runnable() {

    @Override

    public void run() {

    try {

    // Your network activity

    // code comes here

    } catch (Exception e) {

    e.printStackTrace();

    }

    }

  });

 demoThread.start();

 


Method #5: Using android annotations

You can also use the android annotations to fix this error . Below code to your Java file and see things move!

 private void demo()

 {

     fetchData();

     // Add code which needs to

  }

 

 @Background

 protected void fetchData()

 }


Happy coding!







365Bloggy May 20, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive