Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Write and Get Object

Tags:

android

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

like image 459
Flynn Avatar asked May 20 '12 00:05

Flynn


1 Answers

First of all your object must implement Serializable. Don't forget to add a serialVersionUID on the serializable class.

Then if you don't want to save specific field of the object mark it as transient. Be sure all fields are serializable.

Next create a file in the 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 that path to save your object:

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

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

Reading is similar:

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

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

in.close();
like image 174
Tiago Almeida Avatar answered Oct 21 '22 15:10

Tiago Almeida