Дмитрий
Дмитрий

Reputation: 11

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

I have a problem when I want to record into Room database my JSON.

My data class is:

data class CurrentWeatherEntry(
@SerializedName("temperature")//
val temperature: Int,
@SerializedName("weather_code")
val weatherCode: Int,
@SerializedName("weather_icons")
val weatherIcons: List<String>,

)

{
    @PrimaryKey(autoGenerate = false)
    var id : Int = CURRENT_WEATHER_ID
}

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

private final java.util.List<java.lang.String> weatherIcons = null;

How to create converter?

Upvotes: 1

Views: 109

Answers (1)

Andrew
Andrew

Reputation: 4732

object Converter {
   private val gson = Gson()
   private val listTypeConverter = object : TypeToken<List<String>>() {}.type

   @TypeConverter
   @JvmStatic
   fun fromListToIcon(list: List<String>): String = gson.toJson(list, listTypeConverter)

  @TypeConverter
  @JvmStatic
  fun fromIconToList(icon: String): List<String> = gson.fromJson(icon, listTypeConverter)
}

Then add @TypeConverters(Converter::class) at the top of your DataBase:

@TypeConverters(Converter::class)
abstract class YourDB : RoomDatabase()

Upvotes: 1

Related Questions