What is the TypeConverter

TypeConverter is a TypeConverter for the Room database that can convert received data

Such as:

If the server returns an array of objects, Room cannot handle arrays by default. In this case, we can use TypeConverter to convert an array of objects from Json to an object

Use TypeConverter to store arrays and dates

Start by defining a Student class and a Book class

A Student can have more than one Book, so our Student construct has a List of books:List


@Entity
data class Book(var name: String) {
    @PrimaryKey(autoGenerate = true)
    var id: Long? = null
}

@TypeConverters(BookConvert::class, DateConverter::class)// If there is no annotation, the compiler will not be able to pass
@Entity
data class Student(var name: String, var books: List<Book>, var date: Date) {
    @PrimaryKey(autoGenerate = true)
    var id: Long? = null
}
Copy the code

Use BookConvert to store the Book array


class BookConvert {
    private val gson = Gson()

    @TypeConverter
    fun objectToString(list: List<Book>): String {
        return gson.toJson(list)
    }

    @TypeConverter
    fun stringToObject(json: String?).: List<Book> {
        val listType: Type = object : TypeToken<List<Book>>() {}.type
        return gson.fromJson(json, listType)
    }
}
Copy the code

Use DateConverter for date and timestamp conversions

class DateConverter {
    @TypeConverter
    fun revertDate(value: Long): Date {
        return Date(value);
    }

    @TypeConverter
    fun converterDate(value: Date): Long {
        returnvalue.time; }}Copy the code

Data storage results

other

How do I add TypeConverter to multiple objects

Add annotations to the Datebase object

@Database(entities = arrayOf(User::class), version = 1)
    @TypeConverters(Converters::class)
    abstract class AppDatabase : RoomDatabase() {
        abstract fun userDao(a): UserDao
    }
    

Copy the code