Tuesday, April 19, 2011

Why do you get android.os.NetworkOnMainThreadException?

This exception is only thrown for applications targeting the Honeycomb (Android 3) SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness. See API documentation at below link for more information:

Link: http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

How to fix it?

You must either use a handler or a AsyncTask. Check out this site for tutorials (http://www.vogella.de/articles/AndroidPerformance/article.html).

I used the AsyncTask method. I created a CustomAsyncTask class, Extended AsyncTask class and just put everything inside the doInBackground(String[]) method. Once created, a task is executed very simply: new CustomAsyncTask().execute(...);
 
It till need to fine tune my logic to work with AsyncTask but at least I was able to make my code work.

You can also use StrictMode to detect such issues. StrictMode is a developer tool which detects things you might be doing by accident and brings them to your attention so you can fix them.
StrictMode is most commonly used to catch accidental disk or network access on the application's main thread, where UI operations are received and animations take place. Keeping disk and network operations off the main thread makes for much smoother, more responsive applications. By keeping your application's main thread responsive, you also prevent ANR dialogs from being shown to users.

If you find violations that you feel are problematic, there are a variety of tools to help solve them: threads, Handler, AsyncTask, IntentService, etc. But don't feel compelled to fix everything that StrictMode finds.

StrictMode is not a security mechanism and is not guaranteed to find all disk or network accesses. While it does propagate its state across process boundaries when doing Binder calls, it's still ultimately a best effort mechanism.
To know more about StrickMode visit link: http://android-sdk.appspot.com/reference/android/os/StrictMode.html

3 comments:

  1. Thank you very much for the post. It helped me tonight.

    ReplyDelete
  2. hi..Im college student, thanks for sharing :)

    ReplyDelete