How to fix NetworkonMainThreadException in Android? [duplicate] How to fix NetworkonMainThreadException in Android? [duplicate] android android

How to fix NetworkonMainThreadException in Android? [duplicate]


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


Updated Answer:

Potentially long running operations such as network operations should be done in a worker thread.

The most effective way to create a worker thread for longer operations is with the AsyncTask class. Simply extend AsyncTask and implement the doInBackground() method to perform the work.

Many libraries are available to do network operations such as Volley, retrofit etc.


Old Answer:

Add following lines in your activity onCreate method

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


Use following code.

private class UpdateTask extends AsyncTask<String, String,String> {     protected String doInBackground(String... urls) {        DefaultHttpClient httpClient = new DefaultHttpClient();        HttpPost httpPost = new HttpPost(url);        HttpResponse httpResponse = httpClient.execute(httpPost);        HttpEntity httpEntity = httpResponse.getEntity();        is = httpEntity.getContent();        return null;     } }

and in your ManinActivity Use following code.

new UpdateTask().execute();