I have 2 fragment, LoginFragment
and SignUpFragment
.When in SignUpFragment
, click on Android back button at the bottom,it navigate to LoginFragment
.
This is the code for doing so:
SignUpFragment.java
@Override
public void onViewCreated(@NonNull final View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
requireActivity().getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
NavController navController = Navigation.findNavController(view);
navController.popBackStack(R.id.signUpFragment,true);
navController.navigate(R.id.loginFragment);
}
});
}
So this work as expected,I can go back to LoginFragment.java
when click the back button in SignUpFragment.java
.
Problem:
The problem now is,when I in LoginFragment
,I click on the Android back button at the bottom again,I having this error:
java.lang.IllegalStateException: View android.widget.RelativeLayout{3be3bdc V.E...... ......ID 0,0-1080,1962 #7f0a017d app:id/root_layout} does not have a NavController set
at androidx.navigation.Navigation.findNavController(Navigation.java:84)
at com.company.ui.user.SignUpFragment$3.handleOnBackPressed(SignUpFragment.java:128) //WHY THIS LINE??
at androidx.activity.OnBackPressedDispatcher.onBackPressed(OnBackPressedDispatcher.java:189)
at androidx.activity.ComponentActivity.onBackPressed(ComponentActivity.java:286)
As you can see,the error shown is said the error cause by handleOnBackPressed(SignUpFragment.java:128)
,means that it caused by handleOnBackPressed()
function inside SignUpFragment.java
.
But in reality I click the back button when I in LoginFragment.java
.And inside LoginFragment.java
doesnt have any handleOnBackPressed()
function.
I totally having no idea why this behavior could happened?.
Question:
Why is this could happened? What causing this?? And how to solve this??
requireActivity().getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) {
Should be
requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), new OnBackPressedCallback(true) {