For my current application that I'm writing I have implemented a navigation drawer (the default Android way with backwards compatibility). So from the nav drawer you select a menu element and then I do this (addPreviousToBackStack is always false for testing):
private void replaceFragment(final Fragment fragment, final boolean addPreviousToBackStack) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.activity_main_fragment_container, fragment);
if(addPreviousToBackStack) {
fragmentTransaction.addToBackStack(fragment.getTag());
}
fragmentTransaction.commit();
currentFragment = fragment;
}
So that works like a charm when I start the application. Then I close the application using the back button. If I then reopen the app (no matter how: via the long press home button or via the shortcut) the app starts at the initial screen (onCreate is called) and then I open the nav drawer and select a menu item and the application crashes.
This is my exception: "java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState"
And it happens exactly on my line where I do
fragmentTransaction.commit();
I have no clue why I'm getting this when the app is re-opened and not when the app is initially opened. Any clues??
I am not sure what is the context of your use case, but calling fragmentTransaction.commitAllowStateLoss();
should not cause the crash anymore. However, you need to assume the risk that your state info will be lost on fragment.
Also, this line currentFragment = fragment;
seems to me a cause of memory leak. If Android wants to cleanup the fragment you will prevent it by keeping a strong reference to the fragment. Don't use it ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.