I tried to set a type converter for city
at the entity, but there is still the error as in the question title. Let's see at my entity:
@Entity(tableName = "users")
data class UserEntity(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val name: String,
val city: City?
)
Yes, someone can tell me that type converter should be applied to field city
like this:
@TypeConverter(CityConverter::class)
val city: City?
but it is also not works))
Below is my database, City
and CityConverter
@Database(entities = [UserEntity::class], version = 1, exportSchema = false)
// As you can see, I apply type converter here
@TypeConverters(CityConverter::class)
abstract class MyDatabase : RoomDatabase() {
abstract val dao: MyDao
companion object {
@Volatile
private var instance: MyDatabase? = null
fun getInstance(context: Context): MyDatabase {
var currentInstance = instance
if (currentInstance == null) {
currentInstance =
Room.databaseBuilder(context, MyDatabase::class.java, "mydb").build()
instance = currentInstance
return currentInstance
}
return currentInstance
}
}
}
City:
data class City(
val name: String
)
And converter:
class CityConverter {
private val jsonAdapter = Moshi.Builder()
.addLast(KotlinJsonAdapterFactory())
.build()
.adapter(City::class.java)
@TypeConverter
fun cityToString(city: City?): String {
return city?.let { jsonAdapter.toJson(it) } ?: ""
}
@TypeConverters
fun stringToCity(json: String?): City? {
return json?.let { jsonAdapter.fromJson(json) }
}
}
I did all as in the documentation, but it is not work(
Try replacing:
@TypeConverters
fun stringToCity(json: String?): City? {
return json?.let { jsonAdapter.fromJson(json) }
}
with, by removing the s
from @TypeConverters
:
@TypeConverter
fun stringToCity(json: String?): City? {
return json?.let { jsonAdapter.fromJson(json) }
}