T D Nguyen
T D Nguyen

Reputation: 7613

Save OffsetDateTime to Room database

I have a data class with a field of type 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

Upvotes: 0

Views: 528

Answers (1)

Nitish
Nitish

Reputation: 3401

To persist Date Object in Roomdb, you need to use Type Converters

Suppose you need to persist instances of Date in your Room database. Room doesn't know how to persist Date objects, so you need to define type converters:

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

Upvotes: 1

Related Questions