faraz_ahmed_kamran faraz_ahmed_kamran - 2 months ago 14
Android Question

Android null object reference on ProgressBar in dialog

I have the following code where I create a ProgressBar in a dialog:

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]);


And my layout of the ProressBar is the following in
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" />


But I get the following error for line
bar.setProgress(i[0]);
:

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

Answer

If your ProgressBar is inside your dialog you need to change the line

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

for this

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

Good luck!