StrictMode.ThreadPolicy was introduced since API Level 9 and the default thread policy had been changed since API Level 11, which in short, does not allow network operation (eg: HttpClient and HttpUrlConnection) get executed on UI thread. if you do this, you get NetworkOnMainThreadException.

You can easily solve this error. The recommended way of solving this is by Using an AsyncTask so that the network request does not block the UI thread.

Alternatively, you can override this thread policy by adding the below code into your main activity’s onCreate() method.

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

9 Responses to “android.os.NetworkOnMainThreadException due to StrictMode.ThreadPolicy”

  1. dilsha says:

    great its very helpful…….

  2. Willy says:

    I love You 🙂
    I searched 3 days to repair this problem with Android 3 and older.

    PS: My english isn’t good 😀

  3. Thanks so much. I was trying to connect a database and your post has solved my problem

  4. Nilesh Patel says:

    Thanks for help

  5. biju . p m says:

    thxs man . it helped me a lot . g8 thank u thank u thank u

  6. Gaurav Dixit says:

    Thanks Man

    It helped for me.

    Regards as
    Gaurav

  7. Thank you very much
    Sanjeewa

    my problem

    e3 NetworkOnMainThreadException (id=831956467976)
    cause NetworkOnMainThreadException (id=831956467976)
    cause NetworkOnMainThreadException (id=831956467976)
    cause NetworkOnMainThreadException (id=831956467976)
    detailMessage null
    stackState (id=831956468032)
    stackTrace null
    suppressedExceptions ArrayList (id=831956468008)
    detailMessage null
    stackState (id=831956468032)
    stackTrace null
    suppressedExceptions ArrayList (id=831956468008)
    detailMessage null
    stackState (id=831956468032)
    [0] -1299676136
    [1] 15
    [2] -1300866152
    [3] 4
    [4] -1300365480
    [5] 5
    [6] -1300365592
    [7] 0
    [8] -1298756584
    [9] 33
    [10] -1298755680
    [11] 1
    [12] -1300993416
    [13] 63
    [14] -1300993920
    [15] 12
    [16] -1298434024
    [17] 39
    [18] -1300437936
    [19] 1
    [20] -1300150904
    [21] 52
    [22] -1300453608
    [23] 281
    [24] -1300454728
    [25] 32
    [26] -1300456072
    [27] 0
    [28] -1300225496
    [29] 29
    [30] -1300279240
    [31] 20
    [32] -1299683976
    [33] 122
    [34] -1300453776
    [35] 34
    [36] -1301062080
    [37] 0
    [38] -1301060952
    [39] 17
    [40] -1298957232
    [41] 11
    [42] -1300538664
    [43] 66
    [44] -1301042264
    [45] 0
    stackTrace null
    suppressedExceptions ArrayList (id=831956468008)

  8. irfan says:

    Thanks. It helped.

Leave a Reply

*

Search