OnSaveInstanceState with Singleton

I have a Singleton Data class that I use to store data. I refer to him in different Fragment with.

When the first Fragment loaded, there is no problem that all fields in Singleton are null . When the second Fragment displayed, it depends on these fields to show your data. The first Fragment provides initialization of these fields.

However, when the user clicks the home button in the second Fragment and reopens it after an hour or so, Singleton has lost all his data, and Fragment trying to access the null fields.

I wanted to implement the onSaveInstanceState method, but I do not understand how this works - I do not have a data instance for its purpose.

 @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 appreciated.

+6
source share
2 answers

Are fragments placed in the same Activity? If so, why not save the general state in the Activity member and use Activity onSaveInstanceState () and onCreate () to save and restore it. In your snippets you can do ...

 ((MyActivityClass)getActivity()).getSharedState() 

Otherwise, you can make your singleton object a controlling 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"); } 
+1
source

You can watch . onSaveInstanceState is not very appropriate if you need to move large objects.

0
source

Source: https://habr.com/ru/post/920487/


All Articles