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.
Complete code with error handling and added file stream closes. Add it to your class that you want to be able to serialize and deserialize. In my case the class name is
CreateResumeForm
. You should change it to your own class name.Android
interfaceSerializable
is not sufficient to save your objects to the file, it only creates streams.Use it like this in your
Activity
:I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:
Option1:
Option2:
Option 2 is twice quicker than option 1
The option 2 inconvenience is that you have to make specific code for read:
I just made a class to handle this with Generics, so it can be used with all the object types that are serializable:
Saving (w/o exception handling code):
Loading (w/o exception handling code):