Possible Duplicate:
Parcelable where/when is describeContents() used?
What is the purpose of implementing describeContents() function of Parcelable interface? Most of the framework code returns 0 as implementation. Documentation says "a bitmask indicating the set of special object types marshalled by the Parcelable." Could someone explain about this function.(probably with an example)
The Parcelable interface adds methods to all classes you want to be able to transfer between activities. These methods are how parcelable deconstructs the object in one activity and reconstructs it in another.
A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.
Parcelable and Bundle objects are intended to be used across process boundaries such as with IPC/Binder transactions, between activities with intents, and to store transient state across configuration changes.
Parcel able is faster than serializable. Parcel able is going to convert object to byte stream and pass the data between two activities. Writing parcel able code is little bit complex compare to serialization. It doesn't create more temp objects while passing the data between two activities.
It may happen that your class will have child classes, so each of child in this case can return in describeContent()
different values, so you would know which particular object type to create from Parcel
. For instance like here - example of implementation of Parcelable
methods in parent class (MyParent
):
//************************************************ // Parcelable methods //************************************************ //need to be overwritten in child classes //MyChild_1 - return 1 and MyChild_2 - return 2 public int describeContents() {return 0;} public void writeToParcel(Parcel out, int flags) { out.writeInt(this.describeContents()); out.writeSerializable(this); } public Parcelable.Creator<MyParent> CREATOR = new Parcelable.Creator<MyParent>() { public MyParent createFromParcel(Parcel in) { int description=in.readInt(); Serializable s=in.readSerializable(); switch(description) { case 1: return (MyChild_1 )s; case 2: return (MyChild_2 )s; default: return (MyParent )s; } } public MyParent[] newArray(int size) { return new MyParent[size]; } };
In this case one doesn't need to implement all Parcelable
methods in child classes - except describeContent()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With