Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enums support with Realm?

Tags:

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?

like image 500
MJB22 Avatar asked Jun 23 '16 17:06

MJB22


People also ask

Can enum be used in HashMap?

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.

What can enums be used for?

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.

Does Mongodb support enums?

Enumerations, also known as enums, are not supported natively in the Java SDK.

Does enum support inheritance?

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.


2 Answers

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);   } } 
like image 127
Christian Melchior Avatar answered Sep 28 '22 03:09

Christian Melchior


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

like image 20
Nicolás Carrasco-Stevenson Avatar answered Sep 28 '22 04:09

Nicolás Carrasco-Stevenson