代码之家  ›  专栏  ›  技术社区  ›  Joseph Dailey

AsyncTask内部的android.os.NetworkOnMainThreadException

  •  5
  • Joseph Dailey  · 技术社区  · 11 年前

    我正在构建一个应用程序,并收到NetworkOnMainThreadException 内部 异步任务

    电话:

    new POST(this).execute("");
    

    异步任务:

    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());
    }
    }
    }
    

    日志类别:

    BackgroundError | android.os.NetworkOnMainThreadException
    

    我很困惑为什么这个异常会被抛出到AsyncTask的doInBackground中,有什么想法吗?

    3 回复  |  直到 11 年前
        1
  •  7
  •   David Manpearl    11 年前

    移动 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);
        ...
    }
    
        2
  •  2
  •   SimonSays    11 年前

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

        3
  •  0
  •   Husam A. Al-ahmadi    11 年前

    我认为问题是由于您继承了 MainActivity 进入您的 AsyncTask ,尝试重新调用这部分代码:

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

    既然你不需要它,而且如果你想把任何论点传递给 异步任务 你可以通过 doInBackGround() 方法立即。

    也可以打电话给您 异步任务 使用以下内容 new POST().execute();

    而且你不需要打电话 super.onPostExecute(result); 进入您的 onPostExecute() 方法

    我希望这能有所帮助。