-1

I've been using dialog for the Asynctask progress to show. By doing this, I initialized it inside onPreExecute and dismissed it in onPostExecute. I'm not sure what went wrong when I placed a condition to dismiss only if it's not null and it's showing but still triggered IllegalArgumentException: View not attached to window manager

Here's the code:

  public class SampleTask extends AsyncTask<String, Void, String> {
        public ProgressDialog pDialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(SampleActivity.this);
            pDialog.setMessage(getString(R.string.loading));
            pDialog.setCancelable(false);
            pDialog.show();
        }
        @Override
        protected String doInBackground(String... path) {
            .
            .
            .
        }
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(null);
            if (null != pDialog && pDialog.isShowing()) {
                pDialog.dismiss();
            }
            .
            .
            .
        }
    }

I read here similar solution but would it differ if I place null != pDialog && pDialog.isShowing() together in the same condition?

Community
  • 1
  • 1
Compaq LE2202x
  • 2,030
  • 9
  • 45
  • 62

1 Answers1

0

Your problem is you only accept the android view in main UI Thread. Read this link for more detail So when you call pDialog.dismiss(); in onPostExecute(String), it run on another thread so android throw new IllegalArgumentException. I have some solution for you and hope that help:
1. I alway use this solution but it not good at all:

Handler handler = new Handler();
Runnable runable = new Runnable() {
    @Override
    public void run() {
        // TODO something you would like to do with Android UI.
    }
};
handler.post(runable);

The Handler will create a new thread to run on UI Thread so you can work with Android UI.
2. Sometime I try to use an interface. It more effective than the solution above however, of course, it make me spend more effort.

Trần Đức Tâm
  • 4,037
  • 3
  • 30
  • 58