Why I am getting android.os.NetworkOnMainThreadException with AsyncTask?

大憨熊 提交于 2019-12-09 18:05:08

问题


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?

Here is my Code:

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

    }

And i am calling this class in OnCreate()

new Background_confirmation().execute();

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


回答1:


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

  • 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)

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.




回答2:


You've used wrong AsyncTask method to place Your network related code. Please, move it to doInBackground, because onPreExecute takes place on main thread. So, exception occurred. Details are here.




回答3:


Put all your network request code in doInBackground. onPreExecute and onPostExecute will run on UI Thread (main thead) so you will get an exeption if you request network on these 2 methods.

public class Background_confirmation extends AsyncTask<Void, Integer, Void> {
    @Override
    protected void onPreExecute() {            
        progressDialog = ProgressDialog.show(Confirmation.this,
                "Please wait...", "Retrieving data ...", true);            

    }

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

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

        }
    }

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

    }

}


来源:https://stackoverflow.com/questions/12153762/why-i-am-getting-android-os-networkonmainthreadexception-with-asynctask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!