How to apply Room TypeConverter to a single field of an entity?

青春壹個敷衍的年華 提交于 2021-01-28 19:07:31

问题


I have been trying different solutions for applying a TypeConverter to a single field of a Room database entity but I am getting an error

Cannot figure out how to save this field into database. You can consider adding a type converter for it.

When I apply the converter to the entity like this:

@Entity(tableName = DBKey.calendarDayTable)
@TypeConverters(DateStringConverter::class)
data class CalendarDay(

    @PrimaryKey
    val date: Date
)

everything works as expected, but when I apply it to the field like this:

@Entity(tableName = DBKey.calendarDayTable)
data class CalendarDay(

    @PrimaryKey
    @TypeConverters(DateStringConverter::class)
    val date: Date
)

I get the error mentioned above.

The DateStringConverter class is:

class DateStringConverter {
    private val formatter = SimpleDateFormat("yyyy-MM-dd")

    @TypeConverter
    fun dateFromString(value: String): Date {
        return formatter.parse(value)!!
    }

    @TypeConverter
    fun dateToString(date: Date): String {
        return formatter.format(date)
    }
}

I am using the Room version 2.2.5 and writing the app in Kotlin. The dependencies for Room are:

implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"

Is there a way that I can apply DateStringConverter only to the date field of the CalendarDay entity, or do I have to apply it to the whole entity?


回答1:


You must specify that the annotation should be applied to the field

@field:TypeConverters(DateStringConverter::class)
val date: Date

If you don't specify a use-site target, the target is chosen according to the @Target annotation of the annotation being used. If there are multiple applicable targets, the first applicable target from the following list is used:

  • param (constructor parameter);
  • property;
  • field.

https://kotlinlang.org/docs/reference/annotations.html#annotation-use-site-targets



来源:https://stackoverflow.com/questions/61776375/how-to-apply-room-typeconverter-to-a-single-field-of-an-entity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!