Reputation: 626
I have an app with a single activity and two fragments. Fragment B is added(addedToBackStack) on Top of Fragment A. In Fragment B, I am showing a dialog, going back to Fragment A and then dismissing the dialog. If getActivity()!=null
check is removed inside the handler, the code works fine. But getActivity()
is null inside handler. Why is getActivity()
null inside handler in the following piece of code?
private void showDialog(final Dialog dialog) {
dialog.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (getActivity()!=null && !getActivity().isFinishing()) {
dialog.dismiss();
}
}
}, 1000);
if (getActivity() != null && !getActivity().isFinishing())
getActivity().onBackPressed();
}
Upvotes: 0
Views: 244
Reputation: 21073
getActivity()
is null because after getActivity().onBackPressed();
call your fragment will get detached from the Activity
. So inside handler it will be always null because its getting called with a delay.
If you want to dismiss dialog after one second and also move back to previous fragment then you should move onBackPressed
inside the run method. i have replaced the null check with isAdded()
.
private void showDialog(final Dialog dialog) {
dialog.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (isAdded()) {
dialog.dismiss();
getActivity().onBackPressed();
}
}
}, 1000);
}
Upvotes: 1