In this article I explain a possible cause of android.os.NetworkOnMainThreadException and how to avoid it.
From the Android site you can read:
NetworkOnMainThreadException
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…
Here is a sample developed for Gingerbread, API level 9:
- create an Android project called HttpClient
- edit the file AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="eu.lucazanini.httpclient" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="9" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".HttpClientActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
where <uses-sdk android:minSdkVersion=”9″ /> means an API version earlier to Honeycomb (Gingerbread, API level 9), and <uses-permission android:name=”android.permission.INTERNET”/> authorizes the application to perform an internet connection
- edit the file HttpClientActivity.java
package eu.lucazanini.httpclient; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class HttpClientActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); connect(); } private void connect() { try { DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://www.google.com"); HttpResponse response = client.execute(request); } catch (ClientProtocolException e) { Log.d("HTTPCLIENT", e.getLocalizedMessage()); } catch (IOException e) { Log.d("HTTPCLIENT", e.getLocalizedMessage()); } } }
This app is executed without errors.
If you specify an API level after Honeycomb, such as Ice Cream Sandwich, replacing the line <uses-sdk android:minSdkVersion=”9″ /> with <uses-sdk android:minSdkVersion=”14″ /> and you launch the application, you get the exception android.os.NetworkOnMainThreadException.
An easy way to avoid the exception is to insert the following code (which requires import android.os.StrictMode):
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() .permitAll().build(); StrictMode.setThreadPolicy(policy);
before the row connect() in HttpClientActivity.java
But this method is recommended in development environments only, the recommended method is to use the class AsyncTask.
An example is the following in which the code of the class HttpClientActivity.java is replaced by:
package eu.lucazanini.httpclient; import java.io.IOException; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; //import android.os.StrictMode; import android.util.Log; public class HttpClientActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() // .permitAll().build(); // StrictMode.setThreadPolicy(policy); // connect(); new Connection().execute(); } private class Connection extends AsyncTask { @Override protected Object doInBackground(Object... arg0) { connect(); return null; } } private void connect() { try { DefaultHttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet("http://www.google.com"); HttpResponse response = client.execute(request); } catch (ClientProtocolException e) { Log.d("HTTPCLIENT", e.getLocalizedMessage()); } catch (IOException e) { Log.d("HTTPCLIENT", e.getLocalizedMessage()); } } }
You can override not only doInBackground but also other methods of the AsyncTask class like OnPreExecute(), OnPostExecute(Result), publishProgress(Progress. ..).
30 replies on “The android.os.NetworkOnMainThreadException exception”
Thanks! helpful helpful helpful
very helpful! thank you.
You must be add this command
” if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}”
into protected void onCreate(Bundle savedInstanceState) for check android.os.build program.
something like this.
@SuppressLint(“NewApi”)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// sart this coding.——————————–
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// end coding ————————————
….
Thank you very much for help it is working well
Grazie, hai aiutato anche me! Se usate Xamarin (quindi C#), la sintassi equivalente corretta è:
private class Connection : AsyncTask {
protected override Java.Lang.Object DoInBackground(params Java.Lang.Object[] @params) {
connect();
return null;
}
}
thank you so much for this¡¡ it worked after so much time spent on thinking how to solve it
Thanks for solving my problem. i appreciate for your great help
Thanks
It works for me.
I have tried anything i get but none of that works.
Grazie amico, mi hai aiutato molto con la mia tesi di laurea! 😀
Gracias amigo.
he perdido mas de 10 horas con este problema
Al fin quedo solucionado gracias a ti.!!!!
eress lo maximo. sigue asi.
Thank you!
You helped me after trying this crap (with MySQL Connection) for more than 10 hours!
I am so grateful!
GIVE THIS MAN A COOKIE!
Greets from Austria,
Daniel
[…] http://android-developers.blogspot.in/2009/05/painless-threading.html http://www.lucazanini.eu/2012/android/the-android-os-networkonmainthreadexception-exception/?lang=en […]
“An easy way to avoid the exception is to insert the following code (which requires import android.os.StrictMode):”
Ciao Luca, complimenti per il blog. L’ho conosciuto per sbaglio tramite stackoverflow. Uno degli utenti ha postato questo post come possibile soluzione a un NetworkOnMainThreadException. Dato che utilizzare le policy StrictMode non e’ la soluzione, potresti modificarlo?
thanks…
thanks…you saved my last chance for my thesis project…
Muy buen articulo, sobre la fuente del problema y como resolverlo
saludos desde mexico
Thanks man,,,your article helped me a lot. Keep up the good work
Nice post.. its helped me lot.
Grande articolo!! ho perso 2 giorni per quel problema!
nice one. Thnx…..
nice article!!!!!!
khupach chaan article aahe…nice one article!!!
Questo problema mi ha tolto il sonno per due giorni interi. Grazie per questo bel post!
Grande mi hai salvato…
e quando lo trovavo mai sto problema 🙂
grazie, ti devo almeno un paio d’ore della mia vita
thank you guy! this is very good for me, i’m gonna crazy!
Many thanks for this very useful example ….Grazie
Hi! Thanks for this very helpful post!
grazie mille stavo impazzendo non riuscivo a capire il perchè
mi hai illuminato
nice article!!!!!!