How do I serialize an object and save it to a file in Android?

Ben Lesh picture Ben Lesh · Nov 7, 2010 · Viewed 143.2k times · Source

Say I have some simple class and once it's instantiated as an object I want to be able to serialize its contents to a file, and retrieve it by loading that file at some later time... I'm not sure where to start here, what do I need to do to serialize this object to a file?

public class SimpleClass {
   public string name;
   public int id;
   public void save() {
       /* wtf do I do here? */
   }
   public static SimpleClass load(String file) {
       /* what about here? */
   }
}

This is probably the easiest question in the world, because this is a really simple task in .NET, but in Android I'm pretty new so I'm completely lost.

Answer

Ralkie picture Ralkie · Nov 7, 2010

Saving (w/o exception handling code):

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();
fos.close();

Loading (w/o exception handling code):

FileInputStream fis = context.openFileInput(fileName);
ObjectInputStream is = new ObjectInputStream(fis);
SimpleClass simpleClass = (SimpleClass) is.readObject();
is.close();
fis.close();