I am trying to use onSaveInstanceState method to minimize the server capacity in my app. I am trying to avoid accessing the server everytime the user changes his/her bottom navigation view(now inferred to bnv). (I only could find the examples of onSaveInstanceState when its rotating the phone) I followed every fragment's lifecycle methods but onSaveInstanceState would not be called. I also figured out that when I replace the fragment in BottomNavigationView, let's say, fragmentA to fragmentB, fragmentA reaches onDestroyView when it is replaced. So why won't onSaveInstanceState be called??
I am stuck with this problem for days.. Could anyone give some advice?
My MainActivity codes.
public static final String TAG = "LifeCycles";
FragmentManager manager;
FragmentA fragmentA;
FragmentB fragmentB;
FragmentC fragmentC;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
manager.beginTransaction().replace(R.id.testFrame, fragmentA).commit();
return true;
case R.id.navigation_dashboard:
manager.beginTransaction().replace(R.id.testFrame, fragmentB).commit();
return true;
case R.id.navigation_notifications:
manager.beginTransaction().replace(R.id.testFrame, fragmentC).commit();
return true;
}
return false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.w(TAG, "----- Activity: onCreate ------");
manager = getSupportFragmentManager();
fragmentA = new FragmentA();
fragmentB = new FragmentB();
fragmentC = new FragmentC();
BottomNavigationView navigation = findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
manager.beginTransaction().add(R.id.testFrame, fragmentA).commit();
findViewById(R.id.toActivity).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SemiActivity.class));
}
});
}