Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Here's another approach if, as you say there is a conflict between the Parcelable and Serializable interfaces. (Again, that doesn't make sense, but I'll trust you until I finish my unit tests tomorrow)...

Think about this:

    Parcel p = Parcel.obtain();

    p.writeValue(asset);

    p.setDataPosition(0);

    byte [] b = p.marshall();

    p.recycle();

OOPS, just read the javaDoc for marshall() and it says DO NOT STORE TO DISK. It also says, "Use standard serialization to store to disk" (paraphrase).

So, my first answer should do it for you.

Did you try to use shared preferences? If you need to store key values. Moreover it'll be an XML.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top