AsyncTask中的android.os.NetworkOnMainThreadException

时间:2013-04-25 00:24:22

标签: android android-asynctask http-post networkonmainthread

我正在构建一个应用程序并且正在获取NetworkOnMainThreadException INSIDE 一个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中的do中抛出这个异常,有什么想法吗?

3 个答案:

答案 0 :(得分:7)

JSON代码移至doInBackground()

@Override
protected HttpResponse doInBackground(String... params) {
    ...
    Your current HttpPost code...
    ...
    Gson gSon = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    gSon.fromJson(IOUtils.toString(result.getEntity().getContent()), LogonInfo.class).fill(form);
    ...
}

答案 1 :(得分:2)

result.getEntity().getContent()打开从网络读取的流,因此网络通信在主线程中。将JSON解析移至doInBackground()并仅执行onPostExecute()中的UI任务。

答案 2 :(得分:0)

我认为问题出现了,因为您将MainActivity继承到AsyncTask,尝试重新编写这部分代码:

private MainActivity form;
public POST(MainActivity form){
    this.form = form;
}

由于您不需要它,并且如果您想将任何参数传递给AsyncTask,您可以将其传递给doInBackGround()方法immediatliy。

另外,要致电AsyncTask,请使用以下new POST().execute();

此外,您无需在super.onPostExecute(result);方法中拨打onPostExecute()

我希望这有帮助。