Java – A robust and simple way to save/restore the state of an Android application instance

A robust and simple way to save/restore the state of an Android application instance… here is a solution to the problem.

A robust and simple way to save/restore the state of an Android application instance

In Android, you need to implement the following activity methods so that if the operating system decides to destroy and then recreate your activity, your application can revert to its previous state:

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

The example I’ve seen implementing these methods is using put/getBoolean, put/getInt, etc. on a Bundle object (i.e. primitive only) to save application state. At first, this seems like a very error-prone way to save state, and I don’t see how to scale to store complex objects without writing a lot of code.

What options do I have to store/recover state in a robust and easy-to-implement way?

In case it’s important, my application (game) needs to store about 50 objects, each of which might store 5 floating-point variables and some store references to other objects. I don’t particularly want to write save/restore methods for every class and subclass I use (maybe about 15). It would be ideal if I could put all state-related objects in an object called “state” and then just call save/load on “state” to handle everything.

Is using Java serialization an option? I heard it’s slow, but is this a save/restore issue? Can I write my data to an SD card? To the database?

Related Problems and Solutions