2

I have written an application which sends email from an Android device, but I get the following exception when I try to send an email:

android.os.NetworkOnMainThreadException

Why is this occurring and how can I fix it?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
giusy
  • 365
  • 2
  • 5
  • 17

2 Answers2

8

Which SDK version? If 14+ see this link.

The solution is

JUST FOR DEBUG

Add these rows

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

Real Case

Put the code on an AsyncTask:

private class Connection extends AsyncTask {
    @Override
    protected Object doInBackground(Object... arg0) {

        connect();
        return null;
    }
}

And then call:

new Connection().execute("");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
venergiac
  • 7,469
  • 2
  • 48
  • 70
  • ok thanks solved using the StrictMode – giusy Aug 18 '13 at 09:11
  • Do Not use StrictMode in production Mode, use the AsyncTask – venergiac Aug 18 '13 at 09:12
  • @user2693552 just to add what venergiac is saying - this is _not_ a solution to your issue, it's a workaround to be used so you can test **other parts** of your app are working, and you must move this network operation to another thread later. As your application seems to require this network operation as a critical component, I'd suggest sorting it out now, and not bothering with setting this thread policy. – ataulm Aug 18 '13 at 09:28
  • 1
    The correct mode to call is Connection().execute(""); – vinidog Sep 07 '16 at 18:24
1

This exception means that you are trying to do a network related operation on the main UI thread. You need to do either in a separate thread or in AsyncTask.

The documentation says that:

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 How can I fix 'android.os.NetworkOnMainThreadException'? and Android - android.os.NetworkOnMainThreadException for more.

Something like:

class RetreiveFeedTask extends AsyncTask<String, Void, Void> {

    protected Void doInBackground(String... urls) {
        // Execute the network related option here
    }

    protected void onPostExecute(Void param) {

        // TODO: do something with the feed
    }
}

This is how to execute the task:

new RetreiveFeedTask().execute(urlToRssFeed);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124