Search code examples
javaandroidparcelable

Using Parcelable Interface for Pojo


for my android app i want to use the parcelable interface to save the data when the app is in brackground. I have 3 Float-Values in my class.

It works but when i wake up my app, the values are mixed. That means the value of the third float attribute is now in the first and so on.

Here is my 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];
    }
};

Solution

  • As Durandal said, you need to specify the exact order in which you want to retrieve them when you access the parcel. I think this is what would solve the problem in your case.

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(getmName());
        dest.writeFloat(getPriceStud());
        dest.writeFloat(getPriceEmp());
        dest.writeFloat(getPriceGuest());
    }