DocumentReference.set(Object o) changes boolean field names

Viewed 1222

When using DocumentReference.set(object), boolean fields are changed. Fields with 'is' prefix get changed to normal field value

class Invitation {
    private boolean isRequested;
    private boolean isValid;
    private boolean isAccepted;
    private String lastName,firstName;
    private long sentOn;
}

And when I push this object to the database using set() method the boolean values are changed in this way:

Firestore screenshot

3 Answers

This is an automatic translation so the getter can be named isBoolean rather than getBoolean.

In Android, you can use the @PropertyName annotation to rename a property, which will allow you to specify a different name (in this instance, the exact name), which Firebase should use as is:

class Invitation {
    private boolean isRequested;

    @PropertyName(value="isRequested")
    public boolean isRequested() {
        return this.isRequested;
    }

    @PropertyName(value="isRequested")
    public void setRequested(boolean value) {
        this.isRequested = value;
    }

    // ...
}

However, I would suggest dropping the is prefix on the field names and instead only using it for the getter, like:

public boolean isRequested() {
    return this.requested;
}

We experienced this issue and we solved like this.

boolean isPrimary;

public boolean getIsPrimary() {
    return this.isPrimary;
}

public void setIsPrimary(boolean isPrimary) {
    this.isPrimary = isPrimary;
}

I know it's weird. It seems Firestore uses the 'getter' method to set object, because I first changed the 'setter' method and nothing happened. And I changed 'getter' method and it finally worked correctly.

I hope they fix this issue. Because nobody uses the 'getter' method for boolean as 'getIsSomething' in Android.

In Kotlin, use @field:JvmField. For example,

data class User(
    @field:JvmField
    val isEnrolled: Boolean = false
)
Related