Home > Android, Code, HowTo > Persisting Game Data / A Game State

Persisting Game Data / A Game State

September 12th, 2010 Leave a comment Go to comments

I was thinking about some possibilities storing a more or less “big” GameState. As you may know the InstanceState is transient. If you google the topic you will find the Android Developer Documents about “Saving Persistent State“.

In my opinion the SharedPreferences are “ok” for simple data like Music on / off, or some yes / no / age / gender stuff. But when it comes to more complex data structures you will run into problems.

So let’s see what else we got. There is another solution called Parcelable This works with objects too, but it’s a pain in the *** to implement it for every Object you have in your Pocket.

Another possibility would be to store your data in a SQLite Database. But when you only want to store “one big” Object with lots of sub objects it’s a not to underestimate effort to implement everything you need to get tings stored at the right place.

I came to the conclusion to “keep it simple stupid”. I have a large “GameData” Object with a lot of Object Lists and primitive values and so on ….so i wrote a Singleton Save Service that read/write the Object to a File on the device. Nothing to be proud of, but sometimes in the Android World you loose the sense for the simple Java Stuff that just – works !

package com.androidfactory.service;

public class SaveService {

	private static final String SAVE_FILENAME = "TheSaveFile.ser";

	private GameData saveData;

	private static SaveService saveService;
	private Activity context;

	private FileOutputStream fOut = null;
	private ObjectOutputStream  osw = null;
	private FileInputStream fin = null;
	private ObjectInputStream sin = null;

	public SaveService(Context context){
		this.context = (Activity)context;

	public static SaveService getInstance(Context context){
		if(saveService == null){
			saveService = new SaveService(context);

		return saveService;

	public  void save(GameData object){
		try {
			fOut = context.openFileOutput(SAVE_FILENAME, Activity.MODE_PRIVATE);
			osw = new ObjectOutputStream(fOut);
		} catch (FileNotFoundException e) {
		} catch (IOException e) {


	public GameData readLastState(){
			try {
				fin = context.openFileInput(SAVE_FILENAME);
				sin = new ObjectInputStream(fin);
				saveData = (GameData) sin.readObject();
			} catch (StreamCorruptedException e) {
			} catch (IOException e) {
			} catch (ClassNotFoundException e) {

			return saveData;
  1. No comments yet.
  1. No trackbacks yet.