Wednesday, June 29, 2011

Object Serialization in Android

For my current project I wanted to create a persistent list of applications to be called later. I didn't want to use SharedPreferences because the data is stored as key value pairs.
Serialization can work with any object into a file provided it extends Serializeable. This is very useful for saving custom objects to call later.



This was made from two examples on Java serialization and internal data storage on Android. They can be found here:
http://www.javabeginner.com/uncategorized/java-serialization
http://developer.android.com/guide/topics/data/data-storage.html#filesInternal


In this example I will be saving an ArrayList of strings.



In saveList(object), any object can be serialized provided it implements Serializable. Instead of using FileOutputStream.write(bytes[]) method, ObjectOutputStream will write to the FileOutputStream for us. Change Context.MODE_PRIVATE to fit your needs. See: http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)
To open a previously saved object we will use openList().



openList() returns an ArrayList<String> but it can return whatever object you serialized, adjust accordingly. Like saveList(object), ObjectInputStream will read the data from the FileInputStream instead of using FileInputStream.read().

Once I've got the list opened up I can read data or modify it. When I'm done and want to save it again it's simply a matter of calling saveList(object) again.

1 comment:

  1. Good of you to get people to use serialization to persist state but make sure that they know about the Simple XML Framework and GSON to serialize their objects easily to and from XML and JSON respectively. It has the added bonus of requiring no extra work when they make web services for their app.

    ReplyDelete