dest.writeParcelable(department, flags);当我通过意图包裹对象时,这条线导致应用程序崩溃。
当我评论该行时,应用程序会通过,但当然我没有部门价值。
public class User implements Parcelable {
public String id;
public String name;
public String email;
public Department department;
// other implementations of Parcelable
protected UserVO(Parcel in) {
id = in.readString();
name = in.readString();
email = in.readString();
department = in.readParcelable(Department.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(name);
dest.writeString(email);
dest.writeParcelable(department, flags); // crashes
}
}
部门枚举
public enum Department implements Parcelable {
SALES("Sales", 1),
HR("Human Resources", 2),
SHIPPING("Shipping", 3),
public final String name;
public final int ordinal;
Department(String name, int ordinal) {
this.name = name;
this.ordinal = ordinal;
}
Department(Parcel in) {
name = in.readString();
ordinal = in.readInt();
}
public static final Creator<Department> CREATOR = new Creator<Department>() {
@Override
public Department createFromParcel(Parcel in) {
return Department.valueOf(in.readString()); // crash
//return new DeptEnum(in); // android studio generated code but has error: enum types may not be instantiated
}
@Override
public Department[] newArray(int size) {
return new Department[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(name);
parcel.writeInt(ordinal);
}
}
错误
没有枚举常量 Department.Sales
我从这个答案中得到了帮助return Department.valueOf(in.readString());
温温酱
相关分类