Search code examples
javaandroidurlexceptionnetworkonmainthread

Android NetworkOnMainThreadException when calling Url.OpenStream


I get this exception when running my code on emulator (Android 4.0.3 / API 15). While opening a stream it will throw an exception. Error-message is null.

try {
    String adress        = "xxx";
    URL url              = new URL(adress);
    InputSource source   = new InputSource(url.openStream());

} catch (Exception e) {
    (new TextView).setText("Error: "+e.getMessage());
}

URL is still working with the emulator (in browser).

I have cleaned the project.

Also Internet connection is allowed:

<uses-permission android:name="android.permission.INTERNET" />

Exception : android.os.NetworkOnMainThreadException


Solution

  • Please never run a networking operation on the main (UI) thread .

    Main thread is used to:

    • interact with user.
    • render UI components.

    any long operation on it may risk your app to be closed with ANR message.

    Take a look at the following :

    you can easily use an AsyncTask or a Thread to perform your network operations.

    Here is a great tutorial about threads and background work in android: Link