我一直在尝试将 TypeConverter
应用于 Room 数据库实体的单个字段的不同解决方案,但出现错误
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
当我像这样将转换器应用于实体时:
@Entity(tableName = DBKey.calendarDayTable)
@TypeConverters(DateStringConverter::class)
data class CalendarDay(
@PrimaryKey
val date: Date
)
一切都按预期工作,但是当我将它应用于这样的字段时:
@Entity(tableName = DBKey.calendarDayTable)
data class CalendarDay(
@PrimaryKey
@TypeConverters(DateStringConverter::class)
val date: Date
)
我收到上面提到的错误。
DateStringConverter
类是:
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)
}
}
我正在使用 Room 版本 2.2.5
并使用 Kotlin 编写应用程序。
Room 的依赖项是:
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-ktx:$room_version"
有没有一种方法可以将 DateStringConverter
仅应用于 CalendarDay
实体的 date
字段,或者我是否必须应用它对整个实体?
最佳答案
您必须指定注释应用于该字段
@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
关于android - 如何将 Room TypeConverter 应用于实体的单个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61776375/