Search code examples
androidkotlinenumsgsontypeconverter

How to store Kotlin Enum with Room using Gson in TypeConverter?


I faced problems trying to save Kotlin Enum with Room as JSON (using Gson). I've completely followed official Google instruction and add TypeConverter, but it keeps giving an error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

My entity class:

@Entity(tableName = TextHighlight.TABLE_NAME)
data class TextHighlight.TABLE_NAME(

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = COLUMN_ID)
    var id: Long = 0,

    @TypeConverters(HighlightingColorConverter::class)
    @ColumnInfo(name = COLUMN_HIGHLIGHT)
    var color: HighlightingColor

) {

My Kotlin Enum class:

enum class HighlightingColor(

    @SerializedName("rgb")
    var rgb: String,

    @SerializedName("title")
    var title: String

)

My TypeConverter:

class HighlightingColorConverter {

    @TypeConverter
    fun fromHighlightingColor(highlight: HighlightingColor) = Gson().toJson(highlight)

    @TypeConverter
    fun toHighlightingColor(s: String): HighlightingColor =
        Gson().fromJson(s, HighlightingColor::class.java)

}

Can't understand what's wrong. Please, help to figure it out!


Solution

  • After sometime I've figured how to fix it.

    1. TypeConverter functions should be placed in companion object and has @JvmStatic annotation. It sound logical because these functions should be static in java.
    2. @TypeConverters annotation should be placed not above entity filed, but above hole entity data class.

    Final code is:

    @TypeConverters(TextHighlight.HighlightingColorConverter::class)
    @Entity(tableName = TextHighlight.TABLE_NAME)
    data class TextHighlight(
    
        @PrimaryKey(autoGenerate = true)
        @ColumnInfo(name = COLUMN_ID)
        var id: Long = 0,
    
        @ColumnInfo(name = COLUMN_HIGHLIGHT)
        var color: HighlightingColor
    
    ) {
    
        class HighlightingColorConverter {
    
            companion object {
    
                @JvmStatic
                @TypeConverter
                fun fromHighlightingColor(highlight: HighlightingColor) = Gson().toJson(highlight)
    
                @JvmStatic
                @TypeConverter
                fun toHighlightingColor(s: String): HighlightingColor =
                    Gson().fromJson(s, HighlightingColor::class.java)
    
            }
    
        }
    
    }