Search code examples
androidexceptiontabssmartphone

android.os.NetworkOnMainThreadException on Toshiba Thrive tab, but not on Samsung Duos smartphone


In "onCreate" method, I have a line of code,

Drawable.createFromStream(((java.io.InputStream) new java.net.URL(url).getContent()), "");

When I run it on smartphone(Samsung Duos), it works well. But when I run it on Toshiba Thrive tablet, I get "android.os.NetworkOnMainThreadException" exception.
Why does it happen?


Solution

  • In the newer versions of Android since 3.0, you can't run Network activities on the Main UI thread. Those get killed automatically, as it leads to a bad user experience anyway.

    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.

    NetworkOnMainThreadException

    Run it on a different thread, maybe use AsyncTask