OnSaveInstanceState with Singleton
android, java, singleton
Solution
Are the fragments both hosted in the same Activity? If so, why not store the shared state in a member of the Activity, and use the Activity's onSaveInstanceState() and onCreate() to save and restore it. In your fragments you can then do...
((MyActivityClass)getActivity()).getSharedState()
Otherwise, you could make your singleton object manage a member object that can be serialized and deserialized:
MySingleton.instance().saveTo(outState);
MySingleton.instance().restoreFrom(savedInstanceState);
MySingleton.instance().getState();
Where
public void restoreFrom(Bundle savedInstanceState) {
mState = savedInstanceState.getSerializable("DATA");
}
Problem
I have a Singleton Data class, which I use to store data. I'm accessing it in different `Fragment`s. When the first `Fragment` is loaded, it's no problem that all fields in the Singleton are `null`. When the second `Fragment` is shown, it depends on these fields to show its data. The first `Fragment` ensures these fields are initialized. However, when the user presses the home button in the second `Fragment`, and opens it again after like an hour or so, the Singleton has lost all its data, and the `Fragment` tries to access `null` fields. I wanted to implement the `onSaveInstanceState` method, but I'm stumped on how this works - I have no instance of the data to assign it to. ``` @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("DATA", Data.getInstance()); } @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); savedInstanceState.getSerializable("DATA"); //What to do with this? } ``` Any help is welcome.