Rick Grimes The Coder Rick Grimes The Coder -3 years ago 108
Android Question

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

Requirement: Find out if

is null. Since a primitive float data type cannot be checked for null since its always 0.0, I opted out to use
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();

public void writeToParcel(Parcel parcel, int i) {

However, since the class also implements
, the
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:


How can I use the
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.

Answer Source

You can handle it in the below manner.

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

To read the value of float -

unit_price = in.readByte() == 0x00 ? null : in.readFloat();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download