Android: ProgressDialog failing

2019-08-10 16:59发布

问题:

I'm having real problems getting a ProgressDialog up and running. My code:

ProgressDialog dialog;

try {
  dialog = new ProgressDialog(context);
  dialog.setCancelable(true);
  dialog.setMessage("Loading ...");
  // set the progress to be horizontal
  dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  // set the bar to the default value of 0
  dialog.setProgress(0);

  // set the maximum value
  dialog.setMax(100);
  // display the progressbar
  dialog.show();
 }
catch (Exception e1)
 {
   e1.printStackTrace();
 }

Below that I create my background thread to load some stuff and update the progress bar, but it never gets that far. In the stack trace I get "Unable to add window -- token null is not for an application", but the dialog seems (in the debugger) to have all the right things, it isn't null, but I'm getting this error.

Can anyone shine a light on this?

回答1:

What kind of context are you using to create the ProgressDialog?

I think that the ProgressDialog want work with a ApplicationContext. The API is not very correct the constructor should request an Activity instead of a Context.

Try to pass a reference to a Activity to the constructor instead of an regular Context.

Instead of using:

Context context = getApplicationContext();

use

Context context = this;

Or if you are in an inner class of your Activity (a listener, or Task) use:

Context context = MyActivityNameComesHere.this;

See my Issue in the Android Bugtracker about this.