为什么我通过AsyncTask收到android.os.NetworkOnMainThreadException?

问题描述:

在AsynkTask中编写了网络操作代码时,我正在获取android.os.NetworkOnMainThreadException.还有其他引发此异常的原因吗?

I am getting android.os.NetworkOnMainThreadException while I have wrote the code of networking operation in AsynkTask. is there any other reason for throwing this exception?

这是我的代码:

public class Background_confirmation extends AsyncTask<Void, Integer, Void> {
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            progressDialog = ProgressDialog.show(Confirmation.this,
                    "Please wait...", "Retrieving data ...", true);
            try {
                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httppost = new HttpPost(
                        "http://68.121.167.160/sip_chat_api/create_account.php?useralias="
                                + useralias + "&cntname=" + cntcode + "");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                    is = entity.getContent();


            } catch (Exception e) {
                e.printStackTrace();
            }
            if (backgroung_flag == 1) {

            } else {
                if (is != null) {
                    try {
                        BufferedReader reader = new BufferedReader(
                                new InputStreamReader(is, "UTF-8"));
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        is.close();

                        result = sb.toString();
                    } catch (Exception e) {
                        Log.e("log_tag",
                                "Error converting result " + e.toString());
                    }
                }

            }
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
                // progressDialog.setCancelable(true);
            }
            super.onPostExecute(result);
        }

    }

我正在OnCreate()中调用此类

And i am calling this class in OnCreate()

new Background_confirmation().execute();

但是它总是在Catch块中出现,并给我例外情况

But it always goes in Catch block and gives me this exceptions LogCat
Any suggestion and idea will be Appreciated.
Thanks

public class Background_confirmation extends AsyncTask<Void, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog = ProgressDialog.show(Confirmation.this, "Please wait...", "Retrieving data ...", true);

        }

        @Override
        protected String doInBackground(Void... params) {

            try {
                HttpClient httpclient = new DefaultHttpClient();

                HttpPost httppost = new HttpPost("http://68.121.167.160/sip_chat_api/create_account.php?useralias=" + useralias + "&cntname=" + cntcode + "");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();

            } catch (Exception e) {
                e.printStackTrace();
            }
            if (backgroung_flag == 1) {

            } else {
                if (is != null) {
                    try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                            sb.append(line + "\n");
                        }
                        is.close();

                        result = sb.toString();
                    } catch (Exception e) {
                        Log.e("log_tag", "Error converting result " + e.toString());
                    }
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

            if (progressDialog.isShowing()) {
                progressDialog.dismiss();
                // progressDialog.setCancelable(true);
            }
        }
    }

您的代码应如上所述进行更改.您必须考虑的事情

Your code should change like above. Things you have to consider

  • 连接性应在doInBackground()
  • 内部进行编码
  • 如果要获取doInBackground()的结果,则必须将其放入onPostExecute()
  • 这意味着您必须在doInBackground()中返回一个String值,其中AsyncTask类的第三个参数也应为String(这不是韦恩的答案)
  • Connectivity should code inside doInBackground()
  • If you want to get the result of the doInBackground(), you have to take it in onPostExecute()
  • That means you have to return a String value in doInBackground() where your third parameter of AsyncTask class should be String too (which is not in Wayne's answer)

在您的代码中,您正在调用InputStream,除"else"部分外,我们看不到.如果仅使用InputStream,请确保代码始终到达else部分.

In your code, you are calling a InputStream that we cannot see except in the "else" part. If you are using only that InputStream, make sure code always reach the else part.