My app has a bottom navigation bar which can open contents, search and recent fragments. Hence, you can inflate an "inner" fragment through finding it in the contents list, searching it up or finding it in recents.
Based on how you got to this "inner" fragment, I want to navigate to the contents/search/recent fragment when the back button is pressed. Hence, I implemented an onBackPress interface, similar to this article: https://stackoverflow.com/a/46425415. This worked well.
I then tried to modify the onBackPress implemented in the "inner" fragment as follows:
@Override
public boolean onBackPressed() {
bottomNavigationView = bottomNavigationView.findViewById(R.id.bottomNav);
if (getView() != null && bottomNavigationView.getSelectedItemId()==R.id.nav_content) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragmentContainer, new ContentFragment());
fr.commit();
return true;}
else if (getView() != null && selectedItemId==R.id.nav_recents) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragmentContainer, new FragmentRecents());
fr.commit();
return true;
} else if (getView() != null && selectedItemId==R.id.nav_search) {
FragmentTransaction fr = getFragmentManager().beginTransaction();
fr.replace(R.id.fragmentContainer, new FragmentSearch());
fr.commit();
return true;
} else {return false;}
This caused the app to crash when i press back.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View com.google.android.material.bottomnavigation.BottomNavigationView.findViewById(int)' on a null object reference
I'm not sure why this is the case. Is it because I can only observe bottom navigation view from main activity, but not from a fragment? If anyone has any suggestions, please let me know! thanks!