In an activity, I have got two separate fragments (for simplicity let say fragment x and fragment y). This is how I’m navigating using navigation graphs:
x -> y (Button)
x <- y (System Back button, Action Bar Back Button)
There is a button on y (say z), which when clicked shows you a snackbar. But when I go back by using either of the two back buttons, and then again navigate to y from x, and when I again click z, it crashes my app giving me the following error:
Error: Fragment y did not return a View from onCreateView() or this was called before onCreateView().
This is how I call the snackbar:
snackbarUtil.showErrorSnackbar(strings[0], strings[1], requireView(), requireActivity());
This is how I navigate back:
requireActivity().getOnBackPressedDispatcher().addCallback(new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
if (isEnabled()) {
setEnabled(false);
navigationUtil.navigateBack();
}
}
});
and this:
requireActivity().addMenuProvider(new MenuProvider() {
@Override
public void onCreateMenu(@NonNull Menu menu, @NonNull MenuInflater menuInflater) {
}
@Override
public boolean onMenuItemSelected(@NonNull MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
navigationUtil.navigateBack();
return true;
}
return SignupOne.super.onOptionsItemSelected(menuItem);
}
});