Question

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

Was it helpful?

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

OTHER TIPS

Works for me:

Manifest.xml:

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

.java:

private static boolean DEVELOPER_MODE = true;
...
protected void onCreate(Bundle savedInstanceState) {

     if (DEVELOPER_MODE) {
         StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                 .detectDiskReads()
                 .detectDiskWrites()
                 .detectNetwork()   // or .detectAll() for all detectable problems
                 .penaltyLog()
                 .build());
         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                 .detectLeakedSqlLiteObjects()
                 .detectLeakedClosableObjects()
                 .penaltyLog()
                 .penaltyDeath()
                 .build());
     }  
...

hope it helps.

see also : http://developer.android.com/reference/android/os/StrictMode.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top