Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 793
Juned Avatar asked Aug 28 '12 06:08

Juned


People also ask

Is AsyncTask deprecated in Android?

This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.

What is AsyncTask android?

Android AsyncTask is an abstract class provided by Android which gives us the liberty to perform heavy tasks in the background and keep the UI thread light thus making the application more responsive. Android application runs on a single thread when launched.

How to cancel Async task android?

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

How to implement Async task?

Android AsyncTask going to do background operation on background thread and update on main thread. In android we cant directly touch background thread to main thread in android development. asynctask help us to make communication between background thread to main thread.


1 Answers

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.

like image 156
sandrstar Avatar answered Oct 24 '22 12:10

sandrstar