Right now, my app is using a singleton class `UserData' to maintain user preferences and settings. I have it save all data to a JSON file every time a change is made. So, all of my setters call saveToFile().
This is working just fine, but I just don't like doing the save every time a setter is called. I also would rather not have to put code in the various activities and fragments to call the method to save the data themselves.
Ideally, I would like the singleton to save the data when the application is closed (or it is closed/destryed). I also have an Application class for persiting a few objects across activities, but I don't see a callback for when the application is closing or being destroyed.
Is there a reliable way to have the singleton know when it is going to be destroyed so it can save the data at that time? I want to make sure it never loses changes to its user data.
Or, is there a better way to do this than using a Singleton??
Thanks!
EDIT:
SharedPreferences is not a good option, because:
- I have three string array-lists to save, and they only added support for API 11+. JSON handles arrays well.
- It does the same thing anyway, except that it saves it as XML data instead of JSON. Since it saves the data to one file, it would still have to save the whole thing at once, each time a field is updated.
- I think I can do better.
So, I modified my implementation so that my base Activity class overrides onStop() to call onSave() in my Singleton. When a field is modified, it sets a flag, and only saves the data when that flag is set.
The reference to the Singleton is managed by my Application class as a static variable. It reads the data when the app starts.
I also modified it to do the save asynchronously.
I don't see how this can fail, unless Android kills the app without calling any lifecyle methods, due to memory problems.
What do you think?