将多个对象写入包裹

writing multiple objects to parcel

我正在尝试将枚举 'Status' 保存到实现 parcelable 的自定义 class 中。我在网上找到了如何将字符串、整数或枚举保存在一个实现 parcelable 的 class 中,但没有找到如何同时保存这三样东西。如果解决方案很明显,我很抱歉,但我就是想不通。

这是我的枚举的样子:

public enum Status {
    INITIALIZED, UPDATED, DELETED
}

这是我目前所拥有的:

public class Recipe implements Parcelable{
private String id;//this should be an int, same problem
private String recipeName;
private String recipePreperation;
private Status status;
private final static int MAX_PREVIEW = 50;

public Recipe(int parId, String parRecipeName, String parRecipePreperation) {
    this.id = "" + parId;
    this.recipeName = parRecipeName;
    this.recipePreperation = parRecipePreperation;
    this.status = Status.INITIALIZED;
}

public Recipe(Parcel in){
    String[] data = new String[4];

    in.readStringArray(data);
    this.id = data [0];
    this.recipeName = data[1];
    this.recipePreperation = data[2];
    this.status = data[3];//what I intend to do, I know this is wrong
}

public int GetId() {
    return Integer.parseInt(id);
}

public String GetRecipeName() {
    return this.recipeName;
}

public void SetRecipeName(String parRecipeName) {
    this.recipeName = parRecipeName;
}

public String GetRecipePreperation() {
    return this.recipePreperation;
}

public void SetRecipePreperation(String parRecipePreperation) {
    this.recipePreperation = parRecipePreperation;
}

public Status GetStatus() {
    return this.status;
}

public void SetStatus(Status parStatus) {
    this.status = parStatus;
}

public String toString() {
    String recipe = this.recipeName + "\n" + this.recipePreperation;
    String returnString;
    int maxLength = MAX_PREVIEW;

    if (recipe.length() > maxLength) {
        returnString = recipe.substring(0, maxLength - 3) + "...";
    } else {
        returnString = recipe;
    }

    return returnString;
}

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

@Override
public void writeToParcel(Parcel dest, int arg1) {
    dest.writeStringArray(new String [] {
            this.id,
            this.recipeName,
            this.recipePreperation,
            this.status//what I intend to do, I know this is wrong
    });
}

public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
    public Recipe createFromParcel(Parcel in) {
        return new Recipe(in);
    }

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

如何将一个 int、一个字符串数组和一个枚举保存到一个 class 中以实现 parcelable,以便它可以 writeToParcel()?

不需要读写to/from字符串数组。只需将每个字符串和最后的状态写为 Serializable。这就是我修复它的方式。

public Recipe(Parcel in){
    this.id = in.readString();
    this.recipeName = in.readString();
    this.recipePreperation = in.readString();
    this.status = (Status) in.readSerializable();
}

public void writeToParcel(Parcel dest, int arg1) {
    dest.writeString(this.id);
    dest.writeString(this.recipeName);
    dest.writeString(this.recipePreperation);
    dest.writeSerializable(this.status);
}