[英]Empty savedInstanceState Bundle when restoring a Fragment after double Rotation in replacing Fragment
lets call them Fragment A and B. Fragment B is just a detailed view for A which replaces the Fragment A upon a click of a Button in Fragment A. 我们称之为片段A和B.片段B只是A的详细视图,它在片段A中单击按钮时替换片段A.
The replacement code: 替换代码:
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, new DetailFragment());
transaction.addToBackStack(null);
transaction.commit();
When I now rotate the screen in Fragment B once and press Back the old Fragment A gets restored without any problems (it restores it state in onActivityCreated with the savedInstanceState Bundle). 当我现在在片段B中旋转屏幕一次然后按返回时,旧的片段A将恢复而不会出现任何问题(它会使用savedInstanceState Bundle在onActivityCreated中恢复它的状态)。
Now to the fun part... 现在到了有趣的部分......
When I rotate the screen in Fragment B more than once and press Back I get a NullPointerException because int[] data = savedInstanceState.getIntArray(STATE_DATA);
当我在Fragment B中不止一次旋转屏幕并按Back时,我得到一个NullPointerException,因为
int[] data = savedInstanceState.getIntArray(STATE_DATA);
in onActivityCreated
returns null. 在
onActivityCreated
返回null。
How can I fix this behavior? 我该如何解决这个问题? The only other way I though of was through permanent Storage(Preference or DB) but that seems very inappropriate for the use case.
我唯一的另一种方式是通过永久存储(Preference或DB),但这似乎非常不适合用例。
edit/additional info: The bundle itself is not null, it's just empty 编辑/附加信息:包本身不为空,它只是空的
Ok I found the answer: 好的,我找到了答案:
The following methods from Fragment A get called on rotation change while Fragment B is active: onSaveInstanceState(), onAttach() and onCreate() 当片段B处于活动状态时,片段A中的以下方法会在旋转更改时调用:onSaveInstanceState(),onAttach()和onCreate()
because I am restoring my state in onActivityCreated (which is actually recommended by the sdk!) I lose my variables stored in the bundle after the first rotation because they never get loaded into the local variables that then would be stored on the next onSaveInstanceState. 因为我正在onActivityCreated中恢复我的状态(这实际上是由sdk推荐的!)我在第一次旋转后丢失了存储在bundle中的变量,因为它们永远不会被加载到局部变量中,然后存储在下一个onSaveInstanceState中。 Therefore those values are null when I try to retrieve them after the second rotation.
因此,当我尝试在第二次旋转后检索它们时,这些值为null。
Solution: Restore the variables in onCreate() so that they are available when onSaveInstanceState is called again. 解决方案:恢复onCreate()中的变量,以便在再次调用onSaveInstanceState时它们可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.