Computerish
Computerish

Reputation: 9591

ProgressDialog in AsyncTask throws an exception

I'm trying to make a simple ProgressDialog appear while my AsyncTask is fetching data. In my onPreExecute() method I have this:

pd = ProgressDialog.show(c, "Loading...", "Please wait");

c is the context passed into the constructor of my AsyncTask from this.getApplicationContext(). Unfortunately, I keep getting an exception with this message:

Unable to add window -- Token null is not for an application

What am I doing wrong?

Update: Using this instead of this.getApplicationContext() has revealed another problem. When I call ProgressDialog.show(..., a ProgressDialog is displayed, but not until after the AsyncTask has completed. In other words, the data loads and then the dialog is displayed. If I include pd.dismiss() in my onPostExecute() then I never even see the dialog (presumable because it is closed before it ever gets opened).

Final solution: It turns out that fetch.get() was hogging the UI thread and not letting the ProgressDialog display.

Upvotes: 6

Views: 4284

Answers (3)

Yohanes AI
Yohanes AI

Reputation: 3619

Use YourClassName.this instead of using getApplicationContext() or this.getApplicationContext()

Upvotes: 0

Pentium10
Pentium10

Reputation: 207830

ProgressDialog dialog;
@Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(viewContacts.this);
        dialog.setMessage(getString(R.string.please_wait_while_loading));
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }

Upvotes: 4

Jorgesys
Jorgesys

Reputation: 126445

try this

  this.pd = ProgressDialog.show(this,"Loading...", "Please wait", true, false);

and yes I think the same the problem is with your context.

Upvotes: 1

Related Questions