简体   繁体   English

将 OffsetDateTime 保存到 Room 数据库

[英]Save OffsetDateTime to Room database

I have a data class with a field of type OffsetDateTime .我有一个数据类,其字段类型为OffsetDateTime With the room database, I have the following error:使用房间数据库,我有以下错误:

 Cannot figure out how to read this field from a cursor. private final java.time.OffsetDateTime

How can I fix this?我怎样才能解决这个问题? Thanks谢谢

To persist Date Object in Roomdb, you need to use Type Converters要在 Roomdb 中持久化日期对象,您需要使用类型转换器

Suppose you need to persist instances of Date in your Room database.假设您需要在 Room 数据库中保留 Date 的实例。 Room doesn't know how to persist Date objects, so you need to define type converters: Room 不知道如何持久化 Date 对象,所以需要定义类型转换器:

class Converters {
  @TypeConverter
  fun fromTimestamp(value: Long?): Date? {
    return value?.let { Date(it) }
  }

  @TypeConverter
  fun dateToTimestamp(date: Date?): Long? {
    return date?.time?.toLong()
  }
}

Example given here will give you a better idea: Referencing complex data using Room这里给出的例子会给你一个更好的主意: Referenceing complex data using Room

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM