Android - Save Parcelable data into a file

ejay picture ejay · May 8, 2014 · Viewed 12.9k times · Source

I used to use Serializable objects to save them in filesytem and read them in order to do whatever I want. But Serialization is slow when you have to pass data between activities, so I read than it's recommanded to use Parcelable. Then I did it and yeah it's faster ! But now, I have a little problem. Since Parcelable is optimized for IPC, then they aren't serializable and can't be saved into a file. So I would to know if it's possible to do it.

Also, If I decide to implement both Parcelable and Serializable interface for my class, but only use the Parcelable to pass data between my activities, I would be able to save the class into a file. But I guess than since I use serializable (only to save, not to pass data), this is not a good idea hum ?

I thought too to use Gson library, to serialize data from class, and save the JSON into a file, and reuse Gson to deserialize JSON to get my Parcelable object. Does it seems to be a good idea ? What about performance ?

Thanks to all for your answers!

J.

Answer

James Barwick picture James Barwick · Jul 28, 2014

Just do context.getFilesDir() and use a java.io.ObjectInputStream and java.io.ObjectOutputStream.

Also, with regard to "Parcelable not now serializable". This doesn't entirely make a lot of sense since Parcelable in an interface, not a class you extend.

So,

class MyClass implements Parcelable, Serializable {   
}

should work just fine. Once you read and write the object to the file system, the Parcelable interface will still work. It's only an interface.

I have to admit I haven't tried it, but it's what I wrote today and I will be writing the unit test tomorrow.

Hope this helps.