Home > other >  Cannot save list of Integers in Room Database after adding type converter in Database and the entity
Cannot save list of Integers in Room Database after adding type converter in Database and the entity

Time:10-29

My Entity

@Entity(tableName = "doctor_table")
data class DoctorEntity(
    @PrimaryKey(autoGenerate = true)
    var id : Int = AppUtil.defId,
    var doc_id : Int = AppUtil.defId,
    var name : String = AppUtil.defString,
    @field:TypeConverters(IntTypeConverter::class)
    var days : List<Int> = AppUtil.emptyIntArray,
    @field:TypeConverters(LongTypeConverter::class)
    var numbers : List<Long> = AppUtil.emptyLongArray,
    @field:TypeConverters(IntTypeConverter::class)
    var clinic_ids : List<Int> = AppUtil.emptyIntArray
    )

The empty int array : val emptyIntArray = arrayListOf<Int>()

IntTypeConverter class:

class IntTypeConverter {
    @TypeConverter
    fun saveIntList(list: List<Int>): String? {
        return Gson().toJson(list)
    }

    @TypeConverter
    fun getIntList(list: List<Int>): List<Int> {
        return Gson().fromJson(
            list.toString(),
            object : TypeToken<List<Int?>?>() {}.type
        )
    }

DB class:

@Database(
    entities = [DoctorEntity::class, ClinicEntity::class,
        DocClinicEntity::class, DocTreatmentEntity::class,
               TreatmentEntity::class],
    version = 1,
    exportSchema = false
)
@TypeConverters(LongTypeConverter::class,IntTypeConverter::class)

abstract class Db : RoomDatabase() {
    abstract fun getDao(): DbDao
}

I am using hilt to inject the DB @Module @InstallIn(SingletonComponent::class) object AppModules {

@Provides
@Singleton
fun provideDatabase(
    @ApplicationContext app: Context
) = Room.databaseBuilder(
    app,
    Db::class.java,
    "medical_db.db"
).fallbackToDestructiveMigration()
    .build()

}

The error while trying to run the app.

\room\entities\DoctorEntity.java:15: error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
    private java.util.List<java.lang.Integer> days;

What am I missing ??

CodePudding user response:

In your second type convertor, you should input a String instead of a List because you are saving a String representation of you list (according to your first convertor).

Something like this:

@TypeConverter
fun getIntList(list: String): List<Int> {
    return Gson().fromJson(
        list,
        object : TypeToken<List<Int>>() {}.type
    )
}

Also, you need not worry about nullable types here because the list that you are saving in saveIntList is non-nullable and contains non-nullable Ints. So you can safely convert the stored string back to a list which is non-nullable.

  • Related