将多个对象写入包裹

时间:2015-06-05 19:15:00

标签: java android parcelable

我正在尝试保存枚举状态'进入一个实现parcelable的自定义类。我在网上找到了如何在一个实现parcelable的类中保存字符串,整数或枚举,但不是我如何能同时保存这三个东西。如果解决方案很明显,我很抱歉,但我无法弄清楚。

这是我的枚举的样子:

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,字符串数组和枚举保存到实现parcelable的类中,以便它可以写入ToParcel()?

1 个答案:

答案 0 :(得分:3)

无需对字符串数组进行读写操作。只需编写每个字符串,最后将状态写为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);
}