我建立一个应用程序,我得到一个NetworkOnMainThreadException INSIDE一个的AsyncTaskandroid.os.NetworkOnMainThreadException里面的AsyncTask
电话:
new POST(this).execute("");
的AsyncTask:
public class POST extends AsyncTask<String, Integer, HttpResponse>{
private MainActivity form;
public POST(MainActivity form){
this.form = form;
}
@Override
protected HttpResponse doInBackground(String... params) {
try {
HttpPost httppost = new HttpPost("http://diarwe.com:8080/account/login");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email",((EditText)form.findViewById(R.id.in_email)).getText().toString()));
//add more...
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
return new DefaultHttpClient().execute(httppost);
} catch (Exception e) {
Log.e("BackgroundError", e.toString());
}
return null;
}
@Override
protected void onPostExecute(HttpResponse result) {
super.onPostExecute(result);
try {
Gson gSon = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
gSon.fromJson(IOUtils.toString(result.getEntity().getContent()), LogonInfo.class).fill(form);
} catch (Exception e) {
Log.e("BackgroundError", e.toString());
}
}
}
logcat的:
BackgroundError | android.os.NetworkOnMainThreadException
我很困惑为什么这个异常抛出在AsyncTask的doInBackground中做任何想法?
除''doInBackground()'外,'AsyncTask'中的所有内容都在主UI线程上。总体思路是支持常见的用例,比如:在'onPreExecute()'中设置'ProgressBar',在'onProgressUpdate()'中更新'ProgressBar',最后在'onPostExecute )'。所有这些函数都是UI线程安全的,而'doInBackground()'可以安全地花费尽可能多的时间。 – 2013-04-25 00:58:09