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?
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?
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("");
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:
See How can I fix 'android.os.NetworkOnMainThreadException'? and Android - android.os.NetworkOnMainThreadException for more.
Something like:
This is how to execute the task: