Room TypeConverter class fails to compile

194 views Asked by At

I'm attempting to use the Room TypeConverter (Room version 2.2.5) for an enum, but while compiling I receive a Class is referenced as a converter but it does not have any converter methods. Looking at the Converter.java class, it is indeed missing the converter methods I have defined. I've set the annotationProcessorOptions in Gradle to "room.incremental":"true". Has anyone come across this issue before?

enum class Exposure(val label: String) {
    SUN("Sun"),
    PARTIAL_SUN("Partial sun"),
    SHADE_PARTIAL_SUN("Shade, Partial sun"),
    SHADE("Shade"),
    SHADE_SUN("Shade, Sun");

    companion object {
        fun labels(): List<String> {
            return values().map { it.label }.toList()
        }
    }
}
class Converters {
    @TypeConverter
    fun toExposure(value: String): Exposure {
        return value.let { Exposure.valueOf(it) }
    }

    @TypeConverter
    fun fromExposure(exposure: Exposure): String {
        return exposure.name
    }
}
@Entity(tableName = "plant")
data class PlantEntity(
    var name: String,
    var exposure: Exposure
) {
    @PrimaryKey(autoGenerate = true)
    var id: Int = 0
}
@Database(entities = [PlantEntity::class], version = 1, export = false)
@TypeConverters(Converters::class)
abstract class PlantDatabase : RoomDatabase() {

    abstract fun plantDao(): PlantDao

    ...
}
3

There are 3 answers

1
Sylwek845 On

Can you try using object and using @JvmField

object Converters {
    @TypeConverter
    @JvmStatic
    fun toExposure(value: String): Exposure =
        value.let { Exposure.valueOf(it) }


    @TypeConverter
    @JvmStatic
    fun fromExposure(exposure: Exposure): String =
        exposure.name
}
0
hash On

I've faced this issue as well and my enums were nowhere to be found in the compiled java code.

It was because I had placed my enums in a package named enum. This is not allowed as it is a reserved keyword, so I renamed the package to enums. Perhaps you've done something similar, i.e. you've created a package with an illegal name.

On another note, the website you linked says that Room 2.3 and up includes a default type converter for persisting enums.

0
Saghatel Ghara-Ghazaryan On

use this converter class:

class ListConverter {
    @TypeConverter
    fun fromList(list : List<Object>): String {
        return Gson().toJson(list)
    }
    @TypeConverter
    fun toList(data : String) :  List<Object> {
         if (data == null){
             return Collections.emptyList()
         }
         val typeToken = object : TypeToken< List<Object>>() {}.type
         return Gson().fromJson(data,typeToken)
    }
}