'setRetainInstance is deprecated. What is alternative?
setRetainInstance is deprecated. What alternative?
I have a lot of fragments with many complicated object variables inside them.
Today I only have one line of code: setRetainInstance
.
Full code example is below:
public class MyFragment extends Fragment{
private MyComplicatedCustomClass1 object1;
private MyComplicatedCustomClass2 object2;
private MyComplicatedCustomClass3 object3;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
}
This is more than enough to forget about saving and restoring my objects when changing the configuration (for example, when changing the screen rotation).
What should I change in my code for replacing setRetainInstance
?
Please give me a short code example, if possible.
P.S.
ATTENTION: I can read the documentation - so please don't answer in a Google-style manner: "ViewModel is the best... google recommend... and bla-bla...". And please don't copy/paste articles from Google documentation - I can view it myself.
If you have a concrete working code solution - I will very appreciate it.
Solution 1:[1]
I set configChanges in AndroidManifest.xml instead of setRetainInstance in fragment. Activity does not destroy my fragment and objects in it when I flip the orientation.
<activity android:name=".MyActivity"
android:configChanges="screenSize|orientation"
android:label="@string/app_name">
Solution 2:[2]
The correct solution recommended by Google, consists of using a ViewModel, where you'd not only maintain (and restore) the state, but also asyncrhonously push LiveData (or similar). There's also now an additional simple semi-automatic solution in the form of the Saved State Module for ViewModel.
To Quote:
When using this module, ViewModel objects receive a SavedStateHandle object through its constructor. This object is a key-value map that lets you write and retrieve objects to and from the saved state. These values persist after the process is killed by the system and remain available through the same object.
So you should always assume your Fragment (and its UI) are temporary, and will be destroyed at the operating system's earliest convenience. It's up to you to ensure it doesn't depend on state being "magically saved" (like setRetainInstance), and instead write your Fragment in a way where it restores its state based on what the ViewModel offers.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | OLTO and SUGI-cube Project |
Solution 2 | Martin Marconcini |