Showing posts with label NetworkOnMainThreadException. Show all posts
Showing posts with label NetworkOnMainThreadException. Show all posts

Saturday, 16 February 2013

android.os.NetworkOnMainThreadException in android

Hello Droid Guys,

Yesterday , I found a strange issue, my application is running fine on most of
the android devices. But when I run the same application on Samsung S-3, S2,
Samsung Galaxy Duos it will be crashed and give me the error

"android.os.NetworkOnMainThreadException".


Caused by: android.os.NetworkOnMainThreadException
10-30 15:07:35.341: E/AndroidRuntime(732):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)

In my application basically I am showing a alert dialog with an logout button and on click of logout
button I am calling the service. This functionality is not working on above few device
and crashes every time on clickinng the logout button .

After spending a lot of time on it I came to know that on device api version below 9 we 
can call or write  network call in Main UI Thread but above api version 9 it gives error
android.os.NetworkOnMainThreadException. This is happening my  case.

There are Two way to fix this Issue:
    1.Instead of writing network call in Main UI Thread use Async Task.
    2.Add below code into your activity class inside onCreate() method just  after the 

      setContentView(R.layout.activity_main).
      
     if( Build.VERSION.SDK_INT >= 9){
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy); 
     }



Hoping , this will helps you.
Enjoy Coding :)
   

 

Copyright @ 2013 Android Developer Blog.