Interview frequency: …
Short answer
By defining functions annotated with @TypeConverter to convert the custom type to a primitive type SQLite understands (such as text or a number) and reverse it on read.
Explanation
SQLite supports limited types (NULL, INTEGER, REAL, TEXT, BLOB). If you have a field of type Date or List<String> in the entity, you create an intermediary class that converts the date to a Long (timestamp) and back, or converts the list to JSON text, then register the class in the database through @TypeConverters.
Code example
class Converters {
@TypeConverter
fun fromTimestamp(value: Long?): Date? = value?.let { Date(it) }
@TypeConverter
fun dateToTimestamp(date: Date?): Long? = date?.time
}
@Database(entities = [Note::class], version = 1)
@TypeConverters(Converters::class)
abstract class AppDatabase : RoomDatabase()Common mistakes
- Using a TypeConverter to convert whole objects tied by one-to-many relationships instead of creating native tables and relations in the database.