Android http connection exception

Caused by: android.os.NetworkOnMainThreadException

In Honeycomb they’ve gone and put in a trap to catch people trying to do potentially time-consuming network operations on the main thread.

From: 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.

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. See the document Designing for Responsiveness.

Also see StrictMode.

(Please note that you could have instantly found this yourself by doing a web search on the exception at the top of the error messages you posted.)

Because things like looking up a host name can take a long and somewhat indeterminate amount of time, they should not be called from the event functions on the main thread which are required to return quickly (as in within a few milliseconds). If one of these functions takes too long to return, Android loses the ability to send messages to the program, and may pop up the dreaded Application Not Responding dialog.

You should move your networking operations (at least any that require waiting for a result or for a blockage to clear so you can send more) to a thread. If the network operations are coming from an piece of API code, you probably shouldn’t be calling that on the main thread.

Leave a Comment