Search code examples
androidparcelable

Using Float instead of float (Primitive type) when implementing Parcelable


Requirement: Find out if price is null. Since a primitive float data type cannot be checked for null since its always 0.0, I opted out to use Float instead, as it can be checked for null.

public class QOptions implements Parcelable {
    public String text;
    public Float price;
}

protected QOptions(Parcel in) {
    text = in.readString();
    unit_price = in.readFloat();
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(this.text);
    parcel.writeFloat(this.price);
}

However, since the class also implements Parcelable, the writeToParcel crashes with the following exception:

Attempt to invoke virtual method 'float java.lang.Float.floatValue()' on a null object reference

And the exception points to this line:

parcel.writeFloat(this.price);

How can I use the Float data type along with writeToParcel and not cause the exception? Or is there a better way to accomplish my requirement? I just need the price to be null if it's null.


Solution

  • You can handle it in the below manner.

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        if (price == null) {
            dest.writeByte((byte) (0x00));
        } else {
            dest.writeByte((byte) (0x01));
            dest.writeFloat(price);
        }
    }
    

    To read the value of float -

    unit_price = in.readByte() == 0x00 ? null : in.readFloat();