Search code examples
androidsingletondata-persistence

Is using a singleton to store data incorrect in android?


This is a practice I've been using for a while now, but it seem to be deprecated, the literature seems to say that the correct way to save and restore data when the screen goes to the background or rotates is fragments.

I would like your opinion on this

What I've been doing in my apps is create a class I call ApplicationDataHolder()

This has all the variables that define the state of each activity and fragment stored in it.

For example I have an activity that shows a list of tickets and two widgets one for the way to sort the tickets and one to select if it will be ascending or descending.

For this I have created the variables List _tickets, SortOrder _order and boolean _ascending in my DataHolder() and given them default values

Whenever the activity is recreated/created for the first time, I access those variables to set default values (what the default sort order will be, what the initial list will be)

Is this not the optimal way? could this cause problems (for example after the screen has rotated too many times) what is the benefit of using fragments or saveinstancestate/restoreinstancestate over this?

Thanks in advance for any help you can provide


Solution

  • the correct way to save and restore data when the screen goes to the background or rotates is fragments

    Here they are talking about data that is obtained dynamically, either as input data from the user or data coming from a sensor or web-service. This data needs to be restored using onSaveInstanceState() and onConfigurationChanged() when a state change occurs, such as rotation or a tab swipe.

    Initial values can of course be saved in a central global constants file, nothing wrong with that.