Marcel Fuchs
Marcel Fuchs

Reputation: 99

Type converter for Room Database not working on class which has object from another class

I have the following class:

@Entity(tableName = "dutyday_table")
data class DutyDay(
@PrimaryKey
val date: Date,
val showTime: Time,
val  closingTime:Time
)

and another class which uses objects from class "DutyDay":

@Entity(tableName = "tour_table")
data class Tour(
@PrimaryKey
val day1: DutyDay?,
val day2: DutyDay?,
val day3: DutyDay?,
val day4: DutyDay?,
val day5: DutyDay?,
val day6: DutyDay?,
val day7: DutyDay?,
val totalHours: Time
)

and the following converter:

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

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

@TypeConverter
fun longToTime(value: Long?): Time? {
    return value?.let { Time(it) }
}

@TypeConverter
fun timeToLong(date: Time?): Long? {
    return date?.time
}
}

The converter is properly annotated in the database, I have used Room Database and converters before they normaly work fine. But with this example Android Studio is complaining that it cannot figure out how to store the fields from class "Tour", I guess because it uses the DutyDays created in class "DutyDay". Do I somehow have to create another converter for the properties in "Tour"?

Thanks for your help .

Upvotes: 0

Views: 270

Answers (1)

sergiy tykhonov
sergiy tykhonov

Reputation: 5103

There are 3 objects in your entities that are unknown for Room - Date, Time, DutyDay. You've described TypeConverter just for Date and Time, so the problem is that Room doesn't know how to persist DutyDay.

I think you choices are:

  1. Add one more converter for DutyDay (to use Gson-converting to string, for example. Here is link with similar decision).
  2. To use foreign keys inside Tour table instead of DutyDay's references.

Upvotes: 1

Related Questions