Quantcast
Channel: How can I fix 'android.os.NetworkOnMainThreadException'? - Stack Overflow
Viewing all articles
Browse latest Browse all 191

Answer by Kumarsunil for How can I fix 'android.os.NetworkOnMainThreadException'?

$
0
0

Android does not allow a separate process into the main activity thread, and the HTTP connection is an independent thread here. That is the reason you are getting the "android.os.NetworkOnMainThreadException".

There can be a need where you want to check the actual Internet connection before showing webview to the user, because if there is not Internet the web view will show the page not found error to the user, which normally you don't what to show.

For checking Internet availability, the ping command can be used, but in case of Wi-Fi pinging can be disabled at the Wi-Fi server, so in this case you use an HTTP connection to check the status of the request.

This can be the right approach if you are checking your own webview URL link before showing a webview to the user. In this case, you can use the strict mode of Android, but don't permit all the policy because you don't need it.

You should only give network allow policy for the strict mode. Just add the below line into your code, and you will not get this error.

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

Viewing all articles
Browse latest Browse all 191

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>