Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@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(

>Solution :

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) }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading