Purpose of describeContents() of Parcelable interface [duplicate]
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)
Solution 1:
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()