70

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)

Community
  • 1
  • 1
Suresh
  • 9,495
  • 14
  • 49
  • 63

1 Answers1

11

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()

Barmaley
  • 16,638
  • 18
  • 73
  • 146
  • 8
    This answer is not correct. The `Serializable` approach would also work without the use of describeContents(). You use the value to cast a deserialized object to MyParent or one of its subclasses. But the return type of createFromParcel() is MyParent, so you could have simply casted to MyParent in all cases, ignoring the description value. – devconsole Jul 30 '11 at 17:04
  • 21
    Correct answer: [Parcelable where/when is describeContents() used?](http://stackoverflow.com/questions/4076946/parcelable-where-when-is-describecontents-used/4914799#4914799) – devconsole Jul 30 '11 at 17:07
  • No!! As others have said, this is not correct. Android Studio will actually give a compiler error. The value must be either 0 or `CONTENTS_FILE_DESCRIPTOR` according to official docs: https://developer.android.com/reference/android/os/Parcelable.html#describeContents() – HughHughTeotl Dec 19 '17 at 11:34