Search code examples
androidparcel

Why Parcel.writeBoolean(boolean) doesn't exist?


When I need to write a boolean to a Parcel, I do this:

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(myBoolean ? 1 : 0);
}

But, is there any reason for the method writeBoolean not exists?


Solution

  • You could pack your boolean values into a byte using masking and shifting. That would be the most efficient way to do it and is probably what they would expect you to do.

    Check the Primitives section of this link https://developer.android.com/reference/android/os/Parcel.html

    to parcel your boolean values.. you can use http://www.parcelabler.com/

    ex:

    class BooleanSample {
        Boolean flag;
    }
    

    result:

    class BooleanSample implements Parcelable {
        Boolean flag;
    
        protected BooleanSample(Parcel in) {
            byte flagVal = in.readByte();
            flag = flagVal == 0x02 ? null : flagVal != 0x00;
        }
    
        @Override
        public int describeContents() {
            return 0;
        }
    
        @Override
        public void writeToParcel(Parcel dest, int flags) {
            if (flag == null) {
                dest.writeByte((byte) (0x02));
            } else {
                dest.writeByte((byte) (flag ? 0x01 : 0x00));
            }
        }
    
        @SuppressWarnings("unused")
        public static final Parcelable.Creator<BooleanSample> CREATOR = new Parcelable.Creator<BooleanSample>() {
            @Override
            public BooleanSample createFromParcel(Parcel in) {
                return new BooleanSample(in);
            }
    
            @Override
            public BooleanSample[] newArray(int size) {
                return new BooleanSample[size];
            }
        };
    }