使用Parcelable接口为Pojo
问题描述:
为我的android应用程序我想使用parcelable接口来保存应用程序在后台时的数据。我班有3个浮点值。使用Parcelable接口为Pojo
它的工作原理,但当我唤醒我的应用程序时,值是混合的。这意味着第三个float属性的值现在在第一个等等。
这里是我的POJO的Lunch.java:
public class Lunch implements Parcelable {
private String mName;
private float priceStud;
private float priceEmp;
private float priceGuest;
private ArrayList<Lunch> m = new ArrayList<Lunch>();
public static final int PRICE_STUDENT = 0;
public static final int PRICE_EMPLOYEE = 1;
public static int PRICE_GUEST = 2;
public Lunch(Parcel in) {
setmName(in.readString());
setPriceStud(in.readFloat());
setPriceEmp(in.readFloat());
setPriceGuest(in.readFloat());
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getmName());
dest.writeFloat(getPriceGuest());
dest.writeFloat(getPriceEmp());
dest.writeFloat(getPriceStud());
}
public static final Creator<Lunch> CREATOR = new Creator<Lunch>() {
public Lunch createFromParcel(Parcel in) {
return new Lunch(in);
}
public Lunch[] newArray(int size) {
return new Lunch[size];
}
};
答
正如迪朗达尔说,你需要指定要在其中检索它们,当你访问包裹的确切顺序。我认为这是解决你的问题。
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getmName());
dest.writeFloat(getPriceStud());
dest.writeFloat(getPriceEmp());
dest.writeFloat(getPriceGuest());
}
很明显,您需要按照您编写它们的顺序读取值。 – Durandal
@Durandal非常感谢。我一直忽略这一点 – herres