Android NetworkOnMainThreadException

Android has been lenient about network access on the main thread in prior versions and now with ICS, they are cracking down on us.

It is bad practice however to have operations that are intensive and for a network operation it is even more sensitive since the network speed is a varying factor that can block the UI for an unknown amount of time. Although it is annoying to have your app crash all of a sudden in new Android versions because you (and by that I mean, I) made a bad programming mistake, it is for your own good to consider porting your network access code to an AsyncTask. Writing an AsyncTask is shit easy.

private class SomeTask extends AsyncTask<Void, Void, Void>{


protected Void doInBackground(Void…params){

//your network access code goes here



and then in your UI thread or main thread, just instantiate this task and execute it and you’re done. Obviously, I have simplified the AsyncTask by not going into much details about the arguments and result codes etc..You can read all about that here. I can’t tell you how much I love the Android documentation. Say what you want about their fragmentation problem; I just love their documentation. Just amazing. There’s nothing you can’t find in there unlike Apple’s. I spent a whole day trying to figure out how to create those provisioning and distribution certificates and there’s not an article on the internet that ties it all together!

Leave a Reply

Please log in using one of these methods to post your comment: Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.