Android:ProgressDialog失败

Bar*_*rry 1 android progressdialog

我正在尝试使用ProgressDialog并运行它.我的代码:

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();
 }
Run Code Online (Sandbox Code Playgroud)

在下面我创建我的后台线程来加载一些东西并更新进度条,但它永远不会那么远.在堆栈跟踪中,我得到"无法添加窗口 - 令牌null不适用于应用程序",但对话框似乎(在调试器中)拥有所有正确的东西,它不是null,但我得到了这个错误.

任何人都可以对此发光吗?

Jan*_*usz 5

您使用什么样的上下文来创建ProgressDialog?

我认为ProgressDialog希望使用ApplicationContext.API不是非常正确的构造函数应该请求Activity而不是Context.

尝试将对Activity的引用传递给构造函数而不是常规Context.

而不是使用:

Context context = getApplicationContext();
Run Code Online (Sandbox Code Playgroud)

使用

Context context = this;
Run Code Online (Sandbox Code Playgroud)

或者,如果您在Activity(侦听器或任务)的内部类中,请使用:

Context context = MyActivityNameComesHere.this;
Run Code Online (Sandbox Code Playgroud)

见我的问题在Android的错误追踪这件事.