将枚举写入导致 RuntimeException 的 Parcel

Writing an enum to a Parcel causing RuntimeException

我刚刚 post编辑了 ,有人建议我看看另一个答案。在另一个答案中,它告诉我将枚举作为 Serializable 放入包裹中。 (如果你现在不明白我在说什么,请阅读上面的 post。)我试着这样做:

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);
}

当我 运行 我的应用程序时,它崩溃并在行中显示 RuntimeException

operationType = (OperationType)in.readSerializable ();

QuestionOptions(Parcel in) 构造函数中。错误显示 "Parcelable encountered IOException reading a Serializable object (name = )"。我尝试在 SO 上搜索它,我看到 this question 但是那是关于使用列表的,我有一个枚举。我该怎么做?

您必须按照写入顺序从 Parcel 对象中读取内容。首先是布尔数组,其次是 int,然后是枚举值。这个

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

应该做

就像 Blackbelt 提到的 read/write 顺序很重要。

您可以使用枚举的字符串表示形式将其写入 parcel。 要写入布尔变量,您可以使用 writeByte()。 我把你之前 post:

的答案放在这里
protected QuestionOptions(Parcel in) {
    this.operationType = OperationType.valueOf(in.readString());
    this.digitCount = in.readInt();
    this.timerEnabled = in.readByte() != 0;
}

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