Android HttpClient : NetworkOnMainThreadException
On ICS and later you cannot do network operations on the UI thread anymore. Instead you are forced to create a new thread and do your networking stuff there.
Possible tools are Android's AsyncTask
and the normal Java Thread
.
A good tutorial can be found here: Android Threads, Handlers and AsyncTask - Tutorial
HTTP Response in Android - NetworkOnMainThreadException
android.os.NetworkOnMainThreadException
occurs whenever you try to make long running tasks/process on Main UI Thread directly.
To resolve this issue, cover your webservice call inside AsyncTask
. FYI, AsyncTask in android known as Painless Threading which means developer don't need to bother about Thread management. So Go and implement web API call or any long running tasks using AsyncTask, there are plenty of examples available on the web.
Update:
I only want to load webview if http response code is 200.
=> Based on your requirement, I would say include your code inside doInBackground()
method and return status code value, Which you can check inside onPostExecute()
. Now here you are getting status code value 200/201 then you can load WebView.
Android HttpGet android.os.NetworkOnMainThreadException
Exception is clear from the Logs.
Remove "runOnUiThread"
from doInBackground()
.
Network operations must be done in the Background Thread.
Android - android.os.NetworkOnMainThreadException when acess Http client
I dont advise it though but you can use this for test. Refer to @imran khan for good practice.
Add this in your onCreate() method to bypass the checking.
if( Build.VERSION.SDK_INT >= 9){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
How to fix NetworkonMainThreadException in Android?
Your Exception
actually tells you exactly what you are doing wrong. You are not using another thread to perform NetworkOperations. Instead, you perform the network operation on your UI-Thread, which cannot (does not) work on Android.
Your code that connects to the url should be executed for example inside an AsyncTasks doInBackground()
method, off the UI-Thread.
Take a look at this question on how to use the AsyncTask: How to use AsyncTask
Android NetworkOnMainThreadException
You are not allowed to do network operations with the Main (UI) thread.
There are several ways of using background threads.
I would recommend using AsyncTask since it has a nice structure which is easy to understand.
http://developer.android.com/reference/android/os/AsyncTask.html
Here is an SO example also: AsyncTask Android example
Should be a lot more available on Google.
error android.os.NetworkOnMainThreadException
Literally you're doing it wrong.
https://developer.android.com/training/basics/network-ops/index.html
Network operations can involve unpredictable delays. To prevent this
from causing a poor user experience, always perform network operations
on a separate thread from the UI. The AsyncTask class provides one of
the simplest ways to fire off a new task from the UI thread. For more
discussion of this topic, see the blog post Multithreading For
Performance.
https://developer.android.com/training/basics/network-ops/connecting.
bouton.setOnClickListener(new View.OnClickListener() {
public void onClick(View nouveau) {
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2:8080");
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("nom", N));
nameValuePairs.add(new BasicNameValuePair("prenom", P));
nameValuePairs.add(new BasicNameValuePair("email", E));
nameValuePairs.add(new BasicNameValuePair("prevente", B));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
} catch(Exception e) {
Log.e("log_tag", "Error: "+e.toString());
}
return null;
}
}.execute();
}
}
Android - android.os.NetworkOnMainThreadException
NetworkOnMainThreadException: The exception that is thrown when an application attempts to perform a networking operation on its main thread.
You should call sendfeedback method on asynctask then only above code will work. As webserver is taking lot of time to response main thread becomes unresponsive. To avoid it you should call it on another thread. Hence asynctask is better.
here is link that illustrates how to use asynctask
Related Topics
How to Use Roboto Font in Android Project
Running Emulator After Building Android from Source
Android Marshmallow: Test Permissions with Espresso
Oniabpurchasefinished Never Called
Defining a Percentage Width for a Linearlayout
Android: Autocomplete Textview Similar to the Facebook App
How Are Android Activities Handled with Jetpack Compose and Compose Navigation
There Is No Debug.Keystore in .Android Folder
How to Pass Custom Component Parameters in Java and Xml
Post on Facebook Wall Using Facebook Android Sdk Without Opening Dialog Box
Sliding Navigation Drawer Not Handling Clicks on Menu Items Android
How to Implement Multi-Selection and Contextual Actionmode in Actionbarsherlock
How to Implement Google Maps Search by Address in Android
How to Cast Action Provider to Share Action Provider
How to Display Multiple Notifications in Android
How to Display Both Icon and Title of Action Inside Actionbar