Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android firebase 9.0.0 setValue to serialize enums

I have this class making use of enums. Parsing to Firebase json used to work just fine - using Jackson. While migrating to firebase-database:9.0.0 I get the following:

com.google.firebase.database.DatabaseException: No properties to serialize found on class .... MyClass$Kind

where Kind is the enum declared type. The class:

public class MyClass {

    public enum Kind {W,V,U};

    private Double value;
    private Kind kind;

    /* Dummy Constructor */
    public MyClass() {}

    public Double getValue() {
        return value;
    }

    public void setValue(Double value) {
        this.value = value;
    }

    public Kind getKind() {
        return kind;
    }

    public void setKind(Kind kind) {
        this.kind = kind;
    }
}

I suspect Firebase no longer uses Jackson when serializing setValue(new MyClass()).

Is there a way to get enum types serialized? Or some means to be explicit with respect to the serializer method?

like image 815
rmarau Avatar asked May 19 '16 23:05

rmarau


2 Answers

You are right, Firebase Database no longer uses Jackson for serialization or deserialization.

You can represent your enum as a String when talking to Firebase by doing this:

public class MyClass {

    public enum Kind {W,V,U};

    private Double value;
    private Kind kind;

    /* Dummy Constructor */
    public MyClass() {}

    public Double getValue() {
        return value;
    }

    public void setValue(Double value) {
        this.value = value;
    }

    // The Firebase data mapper will ignore this
    @Exclude
    public Kind getKindVal() {
      return kind;
    }

    public String getKind() {
        // Convert enum to string
        if (kind == null) {
          return null;
        } else {
          return kind.name();
        }
    }

    public void setKind(String kindString) {
        // Get enum from string
        if (kindString == null) {
          this.kind = null;
        } else {
          this.kind = Kind.valueOf(kindString);
        }
    }
}
like image 186
Sam Stern Avatar answered Sep 28 '22 01:09

Sam Stern


Just as a side optimizing answer In Android, it is recommended not to use Enums. Use @StringDef or @IntDef, that it could be working without workarounds and you optimized your app for memory.

Very nice video reasoning why: https://www.youtube.com/watch?v=Hzs6OBcvNQE

like image 28
aselims Avatar answered Sep 28 '22 01:09

aselims