How to read/write a boolean when implementing the Parcelable interface? How to read/write a boolean when implementing the Parcelable interface? android android

How to read/write a boolean when implementing the Parcelable interface?


Here's how I'd do it...

writeToParcel:

dest.writeByte((byte) (myBoolean ? 1 : 0));     //if myBoolean == true, byte == 1

readFromParcel:

myBoolean = in.readByte() != 0;     //myBoolean == true if byte != 0


You could also make use of the writeValue method. In my opinion that's the most straightforward solution.

dst.writeValue( myBool );

Afterwards you can easily retrieve it with a simple cast to Boolean:

boolean myBool = (Boolean) source.readValue( null );

Under the hood the Android Framework will handle it as an integer:

writeInt( (Boolean) v ? 1 : 0 );


you declare like this

 private boolean isSelectionRight;

write

 out.writeInt(isSelectionRight ? 1 : 0);

read

isSelectionRight  = in.readInt() != 0;

boolean type needs to be converted to something that Parcel supports and so we can convert it to int.