[英]Android app crashes when reopening and replacing fragment
For my current application that I'm writing I have implemented a navigation drawer (the default Android way with backwards compatibility). 对于我正在编写的当前应用程序,我已经实现了导航抽屉(具有向后兼容性的默认Android方式)。 So from the nav drawer you select a menu element and then I do this (addPreviousToBackStack is always false for testing):
所以从导航抽屉中选择一个菜单元素,然后我这样做(addPreviousToBackStack总是为false进行测试):
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.
如果我然后重新打开应用程序(无论如何:通过长按主页按钮或通过快捷方式)应用程序从初始屏幕开始(onCreate被调用)然后我打开导航抽屉并选择菜单项并且应用程序崩溃。
This is my exception: "java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState" 这是我的例外:“java.lang.IllegalStateException:在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();
我不确定你的用例的上下文是什么,但是调用
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;
另外,这行
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.
如果Android想要清理片段,您将通过保留对片段的强引用来阻止它。 Don't use it ...
不要用它......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.