[Solved] Netwok on main thread exception in android 4.0 [closed]


The reason why your application crashes on Android versions 3.0 and above, but works fine on Android 2.x is because HoneyComb Ice Cream Sandwich and Jelly Bean are much stricter about abuse against the UI Thread. For example, when an Android device running HoneyComb or above detects a network access on the UI thread, a NetworkOnMainThreadException will be thrown:

E/AndroidRuntime(673): java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example/com.example.ExampleActivity}:android.os.NetworkOnMainThreadException

The explanation as to why this occurs is well documented on the Android developer’s site:

A NetworkOnMainThreadException is thrown when an application attempts to perform a networking operation on its main thread. This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it’s heavily discouraged.
Some examples of other operations that JellyBean,ICSandHoneyComb and “ won’t allow you to perform on the UI thread are:

  1. Opening a Socket connection (i.e. new Socket()).
  2. HTTP requests (i.e. HTTPClient and HTTPUrlConnection).
  3. Attempting to connect to a remote MySQL database.
  4. Downloading a file (i.e. Downloader.downloadFile()).

If you are attempting to perform any of these operations on the UI thread, you must wrap them in a worker thread. The easiest way to do this is to use of an AsyncTask, which allows you to perform asynchronous work on your user interface. An AsyncTask will perform the blocking operations in a worker thread and will publish the results on the UI thread, without requiring you to handle threads and/or handlers yourself.

solved Netwok on main thread exception in android 4.0 [closed]