I am a relatively new Android programmer and I was wondering how you could get read text off the internet in 4.0.3. I keep finding code that gives me a Network on Main exception: http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html and was wondering if anyone could provide me some sample code to get around this, for reference I got the code I tried to use here: http://android-er.blogspot.com/2011/04/read-text-file-from-internet-using-java.html. Thanks a lot.
Share
In Honeycomb and Ice Cream Sandwich (i.e. Android 3.0+) , you cannot connect to the internet in the main thread (
onCreate(),onPause(),onResume()etc.), and you have to instead start a new thread. The reason why this has changed is because network operations can make the app wait for a long time, and if you’re running them in the main thread, the whole application becomes unresponsive. If you try to connect from the main thread, Android will throw aNetworkOnMainThreadException.To bypass this, you can run networking code from a new thread, and use
runOnUiThread()to do things in the main thread, such as update the user interface. Generally, you can do something like: