The Ray of Hope The Ray of Hope -4 years ago 91
Android Question

how to solve android.os.NetworkOnMainThreadException in json

This error is occure on only emulator but completely run on mobile...

error

07-30 05:38:09.024: E/AndroidRuntime(941): android.os.NetworkOnMainThreadException

07-30 05:38:09.024: E/AndroidRuntime(941): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)

07-30 05:38:09.024: E/AndroidRuntime(941): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)

07-30 05:38:09.024: E/AndroidRuntime(941): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)

07-30 05:38:09.024: E/AndroidRuntime(941): at libcore.io.IoBridge.connect(IoBridge.java:112)

07-30 05:38:09.024: E/AndroidRuntime(941): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)

07-30 05:38:09.024: E/AndroidRuntime(941): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)

07-30 05:38:09.024: E/AndroidRuntime(941): at java.net.Socket.connect(Socket.java:842)

07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)

07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)

07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)

07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)

07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)

07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)

07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)

07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)

Answer Source

You cannot perform network IO on the UI thread on Honeycombe. Technically it is possible on earlier versions of Android, but is a really bad idea as it will cause your app to stop responding, and can result in the OS killing your app for being badly behaved. You'll need to run a background process or use AsyncTask to perform your network transaction on a background thread.

But still then if you wish to force you app to do it then use the following piece of code,

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

            StrictMode.setThreadPolicy(policy);
        }

But again its not recommendable to use. Read this link for further info.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download