0

I just posted this question and someone suggested that I should look at another answer. In the other answer, it told me to put the enum into the parcel as a Serializable. (And if you don't now what I am talking about, read the post above.) I tried to do it like this:

protected QuestionOptions(Parcel in) {
    digitCount = in.readInt ();
    operationType = (OperationType)in.readSerializable ();
    boolean[] array = new boolean[1];
    in.readBooleanArray (array);
    timerEnabled = array[0];
}

public static final Creator<QuestionOptions> CREATOR = new Creator<QuestionOptions> () {
    @Override
    public QuestionOptions createFromParcel(Parcel in) {
        return new QuestionOptions (in);
    }

    @Override
    public QuestionOptions[] newArray(int size) {
        return new QuestionOptions[size];
    }
};

public QuestionOptions (OperationType operationType, int digitCount, boolean timerEnabled) {
    this.operationType = operationType;
    this.digitCount = digitCount;
    this.timerEnabled = timerEnabled;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    boolean[] array = {timerEnabled};
    dest.writeBooleanArray (array);
    dest.writeInt (digitCount);
    dest.writeSerializable (operationType);
}

When I run my app, it crashes with a RuntimeException in the line:

operationType = (OperationType)in.readSerializable ();

in the QuestionOptions(Parcel in) constructor. The error says "Parcelable encountered IOException reading a Serializable object (name = )". I tried searching this on SO and I see this question however that is about using lists and I have an enum. How can I do this?

Sweeper
  • 213,210
  • 22
  • 193
  • 313

2 Answers2

2

you have to read the content from the Parcel object the same order you write it in. First the boolean array, second the int and then the enum value. This

protected QuestionOptions(Parcel in) {
    boolean[] array = new boolean[1];
    in.readBooleanArray (array);
    timerEnabled = array[0];
    digitCount = in.readInt ();
    operationType = (OperationType)in.readSerializable ();
 }

should do it

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1

Like Blackbelt mentioned the read/write order matters.

You can use the String representation of the enum to write it into parcel. For writing boolean variables you can use writeByte(). I put here the answer from your previous post:

protected QuestionOptions(Parcel in) {
    this.operationType = OperationType.valueOf(in.readString());
    this.digitCount = in.readInt();
    this.timerEnabled = in.readByte() != 0;
}

and

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(this.operationType.name());
    dest.writeInt(this.digitCount);
    dest.writeByte((byte) (this.timerEnabled ? 1 : 0));
}
Blehi
  • 1,990
  • 1
  • 18
  • 20