Search code examples
javaandroidparcelable

How to implement the write & read in Parcelable Class


Parcelable

I have this Player Class:

public class Player implements Parcelable {
private String mName; // Player's name
private Card mCard; // Player's current card
private boolean mLifeStatus = true; // Player's life status
private boolean mProtected = false; // If the Player's been protected by the guard or not
private int mId; // ID of the Player
private int mCount;

/* everything below here is for implementing Parcelable */

// 99.9% of the time you can just ignore this
@Override
public int describeContents() {
    return 0;
}

// write your object's data to the passed-in Parcel
@Override
public void writeToParcel(Parcel out, int flags) {
    out.writeString(mName);
    out.writeValue(mCard);
    out.writeValue(mLifeStatus);
    out.writeValue(mProtected);
    out.writeInt(mId);
    out.writeInt(mCount);
}

// this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
public static final Parcelable.Creator<Player> CREATOR = new Parcelable.Creator<Player>() {
    public Player createFromParcel(Parcel in) {
        return new Player(in);
    }

    public Player[] newArray(int size) {
        return new Player[size];
    }
};

// example constructor that takes a Parcel and gives you an object populated with it's values
private Player(Parcel in) {
    mName = in.readString();
    mCard = in.readValue();
    mLifeStatus = in.readValue(mLifeStatus);
    mProtected = in.readValue(mProtected);
    mId = in.readInt();
    mCount = in.readInt();
}
}

I've tried to fill the last constructor by myself, but I don't know how to read the value of booleans and of custom classes, just like my Card class, which is the Class for the mValue mCard.

I tried to use this but still didn't work: mCard = in.readValue(Card.class.getClassLoader);

How should I write these two methods in order to make the Class implement Parcelable how it's supposed to be?


Solution

  • To write the card

    out.writeParcelable(mCard, flags);
    

    To read the card

    mCard = (Card) in.readParcelable(Card.class.getClassLoader());
    

    To write the Boolean

    out.writeInt(mLifeStatus ? 1 : 0);
    out.writeInt(mProtected ? 1 : 0);
    

    To read the Boolean

    mLifeStatus = in.readInt() == 1;
    mProtected = in.readInt() == 1;
    

    (This is how writeValue and readValue work internally for Boolean types)