I'm working on an android app and Realm, and I need to create an enum attribute for one of my objects; but I discovered in this post that Realm doesn't support enum yet.
My object is like this:
public class ShuttleOption extends RealmObject { private int Id; private String Label; private ShuttleTypes OriginShuttleType; }
and my enum class (ShuttleTypes) corresponds with:
HOME = 1;
and
WORK = 2;
Can anybody suggest me how to do it?
In HashMap, we can use Enum as well as any other object as a key. It doesn't allow storing null key. It allows to store the null keys as well values, but there should be only one null key object and there can be any number of null values. HashMap internally uses the HashTable.
An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are treated as data types, and you can use them to create sets of constants for use with variables and properties.
Enumerations, also known as enums, are not supported natively in the Java SDK.
Enum . Because a class can only extend one parent (see Declaring Classes), the Java language does not support multiple inheritance of state (see Multiple Inheritance of State, Implementation, and Type), and therefore an enum cannot extend anything else.
You can use the pattern described in the issue: https://github.com/realm/realm-java/issues/776#issuecomment-190147079
Basically save it as a String in Realm and convert it going in and out:
public enum MyEnum { FOO, BAR; } public class Foo extends RealmObject { private String enumDescription; public void saveEnum(MyEnum val) { this.enumDescription = val.toString(); } public MyEnum getEnum() { return MyEnum.valueOf(enumDescription); } }
If you need a solution that works on Kotlin you can use the following:
open class Foo: RealmObject() { var enum: MyEnum get() { return MyEnum.valueOf(enumDescription) } set(newMyEum) { enumDescription = newMyEnum.name } private var enumDescription: String = MyEnum.FOO.name }
MyEnum
is the enum declared in @ChristianMelchior answer.
It is worth mentioning that since enum
doesn't have a backing field,it won't be persisted into Realm. There is no need to use the @Ignore
annotation on it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With