I'm following this Medium Article on using fragments with BottomNavigationView:
https://medium.com/@oluwabukunmi.aluko/bottom-navigation-view-with-fragments-a074bfd08711
but the author doesn't go into how to deal with it when Process Death occurs. What am I supposed to do with all the fragment Instance Variables? Because I am getting null pointers when returning to the app after process death.
public class MainActivity extends AppCompatActivity{
private Fragment currentBottomNavFragment;
private FragmentHome fragmentHome;
private FragmentSearch fragmentSearch;
private FragmentProfile fragmentProfile;
}
Edit 1:______________________________
case R.id.bottomnav_home:
Log.d(TAG, "onNavigationItemSelected: " + fragmentHome);
fragmentHome = (FragmentHome) getSupportFragmentManager()
.findFragmentByTag("FRAGMENT_HOME");
if (fragmentHome == null) {
fragmentHome = new FragmentHome();
getSupportFragmentManager().beginTransaction()
.add(R.id.main_fragment_container, fragmentHome, "FRAGMENT_HOME")
.commit();
}else {
Log.d(TAG, "onNavigationItemSelected: Fragment home not null");
Log.d(TAG, "onNavigationItemSelected: " + fragmentHome);
}
return true;
When I simulate process death and click on the home navigation view, the first log.d
Log.d(TAG, "onNavigationItemSelected: " + fragmentHome);
returns a null fragmentHome, however the if else statement is going to the else meaning the fragmentHome is not null. Why am I getting this issue?
Fragment manager has a putFragment
and getFragment
method you can use to save and restore instance state of your Fragments.
This allowed me to save my Fragment Instance Variables so they didn't return null after process death.