简体   繁体   中英

Android Room Type Converter for Custom Object

I'm getting an error while using a list of custom object with Room.

error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

So my data class is like this:

@Entity(tableName = "calorie_daily_table")
data class CalorieDaily(
@PrimaryKey
var date: String,
var breakfast: List<Meal>)

data class Meal(
var foodItem: String,
var foodQuantity: String,
var calorie: Int)

How can i write a TypeConverter to handle this?

So, I've something like this:

class Converter {

var gson = Gson()

@TypeConverter
fun foodItemToString(foodItems: List<FoodItem>): String {
    return gson.toJson(foodItems)
}

@TypeConverter
fun stringToFoodItem(data: String): List<FoodItem> {
    val listType = object : TypeToken<List<FoodItem>>() {
    }.type
    return gson.fromJson(data, listType)
}
}

But, still getting the same error.

You have to add the annotation @Embedded to your second data class Meal

Try adding @TypeConverters before breakfast.

@TypeConverters(Converter::class)
var breakfast: List<Meal>

Updated working code:

@Entity(tableName = "calorie_daily_table")
data class CalorieDaily(
@PrimaryKey
var date: String,
@TypeConverters(Converters::class)
var breakfast: List<Meal>)

data class Meal(
var foodItem: String,
var foodQuantity: String,
var calorie: Int)


class Converter {
var gson = Gson()

@TypeConverter
fun fromBreakfast(mealItems: List<Meal>): String {
return gson.toJson(mealItems)
}

@TypeConverter
fun toBreakfast(data: String): List<Meal> {
val listType = object : TypeToken<List<Meal>>() {
}.type
return gson.fromJson(data, listType)
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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