views:

545

answers:

1

In Android, you need to implement the following Activity methods so your application can be restored to its previous state if the OS decides to destroy then recreate your activity:

public void onSaveInstanceState(Bundle savedInstanceState)
public void onRestoreInstanceState(Bundle savedInstanceState)

The examples I've seen of implementing these methods is to use put/getBoolean, put/getInt etc. on the Bundle object (i.e. primitive objects only) to save the application state. This seems hugely error prone way to save your state for a start and I cannot see how this scales to storing complex objects without writing lots of code.

What options do I have for storing/restoring state in a robust and easy to implement fashion?

In case it's important, my application (a game) needs to store about 50 objects, which each store maybe 5 float variables and some store references to other objects. I don't particularly want to have to write save/restore methods for every class and subclass (maybe about 15 of these) I use. It would be ideal if I could just stick all my state relevant objects in an object called "state" and then just call save/load on "state" to handle everything.

Is using Java serialization an option? I've heard it's very slow, but is that a problem for save/restoring? Could I just write my data to the SD card? To a database?

+2  A: 

Take a look at the Bundle class, it supports storing Parcelable and Serializable. So if you implement one of those interfaces for your state object you should be all set.

Heikki Toivonen
Doh, thanks: Bundle has a "putSerializable" method. Is there a generally agreed upon best way to store objects for this purpose though? For example, I've seen people convert their object to a JSON string and then store/load this string as a bundle. Is serialization really as bad as people make out? What makes it so much slower than normal (if this is true at all)?
BobbyJim
I think converting to JSON would just be wasting computing cycles.
Heikki Toivonen
You should mark answers as accepted; otherwise people may start ignoring your questions since you have such a low accept rate (17% at the moment).
Heikki Toivonen