How to fix NetworkonMainThreadException in Android?
This question already has an answer here:
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
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();
在您的活动onCreate
方法中添加以下行
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
链接地址: http://www.djcxy.com/p/29532.html