Save Bundle to SharedPreferences

Dan picture Dan · Dec 1, 2012 · Viewed 26.2k times · Source

I've gone to great lengths to make all of the data for my Android game fit into a savedInstanceState Bundle. There's a lot of data altogether, including many Parcelable objects. This ensures that when the app is paused or the orientation changes, no data gets lost by the Activity being recreated.

However, I have just recently discovered that a savedInstanceState bundle is apparently NOT appropriate for long-term storage. So I'm looking for a way that I can adapt my existing save method to work as a long-term solution, so that the game state can always be restored.

I have heard of 2 solutions so far:

1) Use the savedInstanceState bundle for orientation changes, but also incorporate SharedPrefs for when the app needs to be shut down completely.

This seems incredibly counter-productive, as it uses 2 different completely methods to do basically the same thing. Also, since my savedInstanceState Bundle uses Parcelable objects, I would have to give each of those objects another method to enable them to be written to SharedPrefs. Essentially LOTS of duplicated and difficult-to-manage code.

2) Serialize the savedInstanceState Bundle and write it directly to a file.

I am open to this, but I don't actually know how to go about doing it. However, I'm still holding onto the hope that there may be a better solution, as I've heard that serialization in Android is "comically / unusably slow".

I would be extremely grateful if someone could provide me with a solution to this.

Answer

Snicolas picture Snicolas · Dec 1, 2012

Funny, this week, the issue 47 of Android Weekly unleashed this library : android complex preferences.

It should fit for you.