Sunday 20 January 2013

NetworkOnMainThreadException

One of the recent issues I found while working with Android 4.0 is NetworkOnMainThreadException.
This is only thrown for applications targeting the Honeycomb SDK (3.0) or higher. Applications targeting earlier SDK versions are allowed to do networking on their main but it's heavily discouraged.

There are some other operations that jelly bean, ICS, HoneyComb won't allow to perform on the UI thread like:
  • HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
  • Opening a Socket connection (i.e. new Socket()).
  • Attempting to connect to a remote MySQL database.
  • Downloading a file (i.e. Downloader.downloadFile()).
 It is recommended not to performing long operations such as network access, database queries or accessing disk on the UI thread.

Solution:
There are three ways to solve the problem of NetworkOnMainThreadException.
  • If you look at android document you will find that from Honeycomb (3.0) they have introduced StrictMode which will not allow network operations on UI thread. So one simple solution is disabling the StrictMode. 
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

But I will not recommend this solution as it will increase load on UI thread with expensive operations like network operation which may freeze your app's UI and freezing UI or lagging in UI will give bad user experience.

  • Second solution is to use AsyncTask<Params, Progress, Result> , using async task you can do all the long running operations which may result in UI lagging if you do those operations on UI thread.
  • Third solution is to use Service. for network operations. Where you required to download data once only when user starts the app in that case I recommend IntentService.
 I hope this will help you, if any body wants to know more about how to use AsyncTask, IntentService or bind Service then please let me know, I will try to help on these.