Android: ProgressDialog failing

╄→尐↘猪︶ㄣ 提交于 2020-01-15 20:12:38

问题


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.



来源:https://stackoverflow.com/questions/7107991/android-progressdialog-failing

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