我刚刚发布了this question,有人建议我再看一下。在另一个答案中,它告诉我将枚举作为Serializable
放入包裹中。 (如果你现在不知道我在说什么,请阅读上面的帖子。)我试着这样做:
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遇到读取Serializable对象(name =)的IOException”。我尝试在SO上搜索这个,然后我看到this question但是这是关于使用列表而且我有一个枚举。我怎么能这样做?
答案 0 :(得分:2)
你必须按照你编写的顺序读取Parcel
对象中的内容。首先是布尔数组,第二个是int,然后是枚举值。此
protected QuestionOptions(Parcel in) {
boolean[] array = new boolean[1];
in.readBooleanArray (array);
timerEnabled = array[0];
digitCount = in.readInt ();
operationType = (OperationType)in.readSerializable ();
}
应该这样做
答案 1 :(得分:1)
就像Blackbelt提到的那样,读/写顺序很重要。
您可以使用枚举的String表示形式将其写入parcel。 要编写布尔变量,可以使用writeByte()。 我把你上一篇文章的答案放在这里:
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));
}