Android: recording and receiving an object

I want to write a serializable object to a file in internal memory. Then I want to load this object from this file later. How can I do this in Android?

+5
source share
1 answer

First of all, your object must implement Serializable. Remember to add serialVersionUIDto the serializable class.

Then, if you do not want to save a specific field of the object, mark it as transient. Make sure all fields are serializable.

Then create a file in internal memory and create an ObjectOutputStream to save your object. If you want to save in a specific folder, you can create a path like this:

File path=new File(getFilesDir(),"myobjects");
path.mkdir();

Then you can use this path to save the object:

File filePath =new File(path, "filename");
FileOutputStream fos = new FileOutputStream(filePath);
ObjectOutputStream oos = new ObjectOutputStream(fos);               

oos.writeObject(object);
oos.close();

Reading is like:

FileInputStream fis = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fis);              

MyObjectClass myObject = (MyObjectClass ) in.readObject();

in.close();
+13

All Articles