5

How to store Java enum classes when using Realm?

From their documentation, it seems like Realm is yet to support storing enums:

Field types Realm supports the following field types: boolean, byte, short, ìnt, long, float, double, String, Date and byte[]. The integer types byte, short, int, and long are all mapped to the same type (long actually) within Realm. Moreover, subclasses of RealmObject and RealmList are supported to model relationships.

There are similar question that was asked for Objective-C and got answered here. None yet for Java though.

Community
  • 1
  • 1
Hadi Satrio
  • 4,272
  • 2
  • 24
  • 45

1 Answers1

6

Without custom methods it is unfortunately slightly cumbersome at the moment, but you can store the string representation instead and convert that to/from the enum.

public enum Foo {
  FOO
}

// V1: Using static methods
public class Bar1 extends RealmObject {
  private String enumValue;

  // Getters/setters

  // Static methods to handle the enum values
  public static Foo getEnum(Bar1 obj) {
    return Foo.valueOf(obj.getEnumValue())
  }

  public static Foo setEnum(Bar1 obj, Foo enum) {
    return obj.setEnumValue(enum.toString());
  }
}

// V2: Use a dummy @Ignore field to create getters/setters you can override yourself.
public class Bar2 extends RealmObject {

  private String enumValue;

  // Dummy field 
  @Ignore
  private String enum;

  public void setEnumValue(String enumValue) {
    this.enumValue = enumValue;
  }

  public String getEnumValue() {
    return enumValue;
  }

  public void setEnum(Foo foo) {
    setEnumValue(foo.toString());
  }

  public Foo getEnum() {
    return Foo.valueOf(getEnumValue());
  }
}
Christian Melchior
  • 19,978
  • 5
  • 62
  • 53