Android – when replacing a fragment, the savedinstancestate bundle is cleared when restoring the fragment after double rotation

We call them fragments a and B. fragment B is just a detailed view of A. it replaces fragment a when a button is clicked in fragment a

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 once in fragment B and press return, the old fragment A will be restored without any problems (it will use savedinstancestate bundle to restore its state in onactivitycreated)

Now comes the interesting part

When I rotate the screen and press back more than once in fragment B, I get a NullPointerException because int [] data = savedinstancestate.getintarray (state_data); Return null in onactivitycreated

How can I solve this problem? My only other way is through persistent storage (preference or dB), but this seems very inappropriate for use cases

Edit / additional information: the package itself is not empty, it is only empty

resolvent:

OK, I found the answer:

When fragment B is active, the following methods in fragment A are called when the rotation changes: onsaveinstancestate(), onattach(), and oncreate()

Because I am restoring my state in onactivitycreated (which is actually recommended by SDK!) I lost the variables stored in the bundle after the first rotation, because they will never be loaded into local variables and then stored in the next onsaveinstancestate. Therefore, when I try to retrieve them after the second rotation, these values are null

Solution: restore the variables in oncreate() so that they are available when onsaveinstancestate is called again

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>