RSS

Android Honeycomb: NetworkOnMainThreadException even when using AsyncTask and no strict mode?

02 Mar

By Jorgesys

I run into a NetworkOnMainThreadException with my Android 3.0 app. Searching for a solution I foundthis, but if I understand this correctly, default setting would be that the strict mode is turned off.

Also, all my network access is in an AsyncTask, so I don’t see the point in this Exception anyway.

So, I’m quite desperate now what I should do to prevent this…

Kind regards, jellyfish

Edit:

This blog entry says that AsyncTask should be enough, but at least clarifies the StrictMode point.

Solution:

I turned off the StrictMode (its probably better to keep some settings but I couldn’t be bothered…):

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

After that, I did run into a “java.lang.RuntimeException: This thread forbids HTTP requests”, but found a solution for this here. I’m a bit confused, though, as AndroidHttpClient worked fine when I used it in my Android 2.0+ app…

Solution, part2

As it turned out, using AsyncTask was a nice idea but pretty useless if done wrong… So there was nothing wrong with the strict mode’s reaction. Should have listened, er? 😉

Still good to know it’s activated on Honeycomb by default.

 

In Android Honeycomb StrictMode is enabled, turn it off adding the code on the onCreate() function…

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main);       
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }

 

Referenced by: http://stackoverflow.com/questions/6277584/android-honeycomb-networkonmainthreadexception-even-when-using-asynctask-and-no/7986490#7986490

Advertisements
 
Leave a comment

Posted by on March 2, 2012 in Android

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: