【问题标题】:Android null object reference on ProgressBar in dialog对话框中 ProgressBar 上的 Android 空对象引用
【发布时间】:2016-09-19 14:44:18
【问题描述】:

我有以下代码在对话框中创建 ProgressBar:

final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.wait_for_response_dialog);

final ProgressBar bar = (ProgressBar) findViewById(R.id.responseWaitBar);
final int[] i = {0};

bar.setProgress(i[0]);

我的 ProressBar 布局如下wait_for_response_dialog.xml

<ProgressBar
        android:id="@+id/responseWaitBar"
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

但我收到bar.setProgress(i[0]); 行的以下错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ProgressBar.setProgress(int)' on a null object reference

【问题讨论】:

  • 如果有帮助,请接受答案。我先回答。
  • 对不起,stackoverflow 说 Gustavo 比你早一分钟...
  • 它说我比他早 2 分钟。
  • 在哪里可以看到这些信息?现在,它只在两个答案上显示“16 小时”...
  • 好吧,我的错。那我改一下正确答案...

标签: android nullreferenceexception android-progressbar


【解决方案1】:

使用dialog 进行初始化。 ProgressBar

final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.wait_for_response_dialog);

final ProgressBar bar = (ProgressBar)dialog.findViewById(R.id.responseWaitBar);
final int[] i = {0};

bar.setProgress(i[0]);

【讨论】:

    【解决方案2】:

    如果您的 ProgressBar 在您的对话框中,则需要更改行

    final ProgressBar bar = (ProgressBar) findViewById(R.id.responseWaitBar);
    

    为此

    final ProgressBar bar = (ProgressBar) dialog.findViewById(R.id.responseWaitBar);
    

    祝你好运!

    【讨论】:

      【解决方案3】:

      避免视图绑定,这是应用程序崩溃的原因。

       ProgressDialog progressDialog = new ProgressDialog(getContext());
                  progressDialog.setMessage("Loading....");
                  progressDialog.setCancelable(false);
                  progressDialog.show();
      

      用它来显示进度条

      【讨论】:

      • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 1970-01-01
      • 2021-07-06
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多