I\'m doing some background work and showing a DialogFragment while I do that. Once my work is done and the relevant callback is invoked, I dismiss the dialog. When I do, I get a
The callback which is invoked is probably on the activity which is or should be destroyed (after orientation change), also the progress dialog might have been instantiated with that same activity. This might cause the NPE. Callbacks on activities should not be invoked from background tasks, to prevent these kinds of problems. Decouple the background task from the activity, for example using otto, or prevent the background task from invoking the (to be) destroyed activity.
This is some code of mine:
static inner class of activity:
public static class ProgressDialogFragment extends DialogFragment {
ProgressDialog dialog;
public ProgressDialogFragment() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dialog = new ProgressDialog(getActivity(), getTheme());
dialog.setTitle(getString(R.string.please_wait));
dialog.setMessage(getString(R.string.uploading_picture));
dialog.setIndeterminate(true);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
return dialog;
}
}
Otto subscription in activity:
@Subscribe
public void onUploadEvent(UploadAvatarEvent uploadAvatarEvent) {
switch (uploadAvatarEvent.state) {
case UploadAvatarEvent.STATE_UPLOADING:
if (!mProgressDialog.isAdded()) {
mProgressDialog.show(getFragmentManager(), TAG_PROGRESS_DIALOG);
}
break;
case UploadAvatarEvent.STATE_UPLOAD_SUCCES:
mProgressDialog.dismiss();
break;
case UploadAvatarEvent.STATE_UPLOAD_ERROR:
mProgressDialog.dismiss();
break;
}
}
onCreate() in activity:
mProgressDialog = (ProgressDialogFragment) getFragmentManager().findFragmentByTag(TAG_PROGRESS_DIALOG);
if (mProgressDialog == null) {
mProgressDialog = new ProgressDialogFragment();
}