Consider this DialogFragment:
public class RollTriggerDialog extends DialogFragment{
private ProgressDialog _dialog;
int _progress;
public Handler _progressHandler;
public RollTriggerDialog() {
// empty
}
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
_dialog = new ProgressDialog(getActivity());
this.setStyle(STYLE_NO_TITLE, getTheme());
_dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
_dialog.setProgress(0);
_progressHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (_progress >= 100) {
_dialog.dismiss();
} else {
_progress++;
_dialog.incrementProgressBy(1);
_progressHandler.sendEmptyMessageDelayed(0,100);
}
}
};
//_progressHandler.sendEmptyMessage(0); <- This uncommented would start the progress
return _dialog;
}
}
It is just a horizontal progressbar with a handler, once the handler receives one message the progressbar goes from 0 to 100.
I am always getting a Null Pointer Exception if I want to trigger that sendEmptyMessage by myself from an activity:
public class MainActivity extends FragmentActivity {
private RollTriggerDialog mRollTriggerDialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
mRollTriggerDialog = new RollTriggerDialog();
mRollTriggerDialog.show(fm, "addDiceDialog_tag");
((RollTriggerDialog)fm.findFragmentByTag("addDiceDialog_tag"))._progressHandler.sendEmptyMessage(0); // <--- NPE HERE!
}
}
If the line of sendEmptyMessage is uncommented in the dialogFragment and the line with NPE in the main activity is commented; the app runs. What is wrong with that invocation?
Note that this is the whole code, excepting manifest and layout files.
The
NullPointerExceptionappears because thefindFragmentByTagreturnsnull. The solution is to callfm.executePendingTransactions()before you use thefindFragmentByTagmethod to execute that fragment transaction right away(see this question for more details).Also, the
Handlerreference will benullat that moment so you’ll want to initialize it in one of the fragment’s lifecycle methods, for example,onCreate: