문제

After I Parcel my Parcelable Object and want to return it back, the values of the variables are all 0.0! Any Idea why?

Here is my Parcelable Class:

public class ParcelData implements Parcelable {

public byte mapIsSelected; 
public byte carIsSelected;
public byte gameIsPaused;
public float positionX ;
public float positionY ;
public float angle;
public int whichMap; 
public int whichCar;



public ParcelData(byte mapIsSelected, byte carIsSelected, byte gameIsPaused, float positionX, float positionY, float angle, int whichMap, int whichCar){


    this.mapIsSelected = mapIsSelected;
    this.carIsSelected = carIsSelected;
    this.gameIsPaused = gameIsPaused;
    this.positionX = positionX;
    this.positionY = positionY;
    this.angle = angle;
    this.whichCar = whichCar;
    this.whichMap = whichMap;
}


public int describeContents() {

    return 0;
}



public void writeToParcel(Parcel dest, int flags) {

    dest.writeByte(mapIsSelected);
    dest.writeByte(carIsSelected);
    dest.writeByte(gameIsPaused);
    dest.writeFloat(positionX);
    dest.writeFloat(positionY);
    dest.writeFloat(angle);
    dest.writeInt(whichCar);
    dest.writeInt(whichMap);

}


private ParcelData(Parcel in) {

    mapIsSelected = in.readByte();
    carIsSelected = in.readByte();
    gameIsPaused = in.readByte();
    positionX = in.readFloat();
    positionY = in.readFloat();
    angle = in.readFloat();
    whichMap = in.readInt();
    whichCar = in.readInt();
}




 public static final Parcelable.Creator<ParcelData> CREATOR = new Parcelable.Creator<ParcelData>() {

        public ParcelData createFromParcel(Parcel in) {
            return new ParcelData(in);
        }

        public ParcelData[] newArray(int size) {
            // TODO Auto-generated method stub
            return new ParcelData[size];
        }
    };
}

and here is how I create the Parcel and than back to Parcelable:

data = new ParcelData((byte)1, (byte)1, (byte)1, 4.0f, 4.0f, 4.0f, 2, 2);
final Parcel parcelData  = Parcel.obtain();
data.writeToParcel(parcelData, 0);

recievedData = ParcelData.CREATOR.createFromParcel(parcelData); 
Log.d ("test", "test: "+ recievedData.positionY);  // always 0.0 ?!?!!?

Thank you

도움이 되었습니까?

해결책

ok finally I have the solution :)

before I use ParcelData.CREATOR.createFromParcel, I need to set the data position of the Parcel back to 0

data = new ParcelData((byte)1, (byte)1, (byte)1, 4.0f, 4.0f, 4.0f, 2, 2);
final Parcel parcelData  = Parcel.obtain();
data.writeToParcel(parcelData, 0);

parcelData.setDataPosition(0) //<----- Solution

recievedData = ParcelData.CREATOR.createFromParcel(parcelData);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top