Friday, November 8, 2013

Android Java Code Fix: StrictMode prevents code execution

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 (include HttpClient and HttpUrlConnection) get executed on UI thread. if you do this, you get NetworkOnMainThreadException.
This restriction can be changed, using:
    if (android.os.Build.VERSION.SDK_INT > 9) {
      StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
      StrictMode.setThreadPolicy(policy);
    }
Add the above code into your main activity's onCreate() method.
In addition, it is always recommended to move network operation off the UI thread, for example, using AsyncTask.

Read more discussions at http://stackoverflow.com/questions/8706464/defaulthttpclient-to-androidhttpclient

No comments:

Post a Comment