Home > Software engineering >  Room Type Convertor causing values not to be saved
Room Type Convertor causing values not to be saved

Time:11-05

When I use a typeconvertor in room for either nested data classes or lists/arraylists ,no values arent saved but when i use the exact code without any field that requires typeconvertors, values are saved in DB (which i can view with App Inspection)

@Entity
data class User(
    @PrimaryKey val uid: Int,
    @ColumnInfo(name = "first_name") val firstName: String?,
    @ColumnInfo(name = "last_name") val lastName: String?,

    //Nested Data Class cause of values not being saved
    @ColumnInfo(name = "WOW") val wow:Wow
)
data class Wow(val a: String,val b:String)

@Dao
interface UserDao {
    @Query("SELECT * FROM user")
    fun getAll():LiveData<List<User>>

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    fun loadAllByIds(userIds: IntArray): List<User>

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND last_name LIKE :last LIMIT 1")
    fun findByName(first: String, last: String): User

    @Insert
    fun insertAll(vararg users: User)

    @Delete
    fun delete(user: User)
}
class TypeConverterWOW(){
    @TypeConverter
    fun listToJson(value:Wow) = Json.encodeToString(value)
    @TypeConverter
    fun jsonToList(value:String) = Json.decodeFromString<Wow>(value)
}
@Database(entities = [User::class], version = 1)
@TypeConverters(TypeConverterWOW::class)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
    companion object{
        //singleton prevents multiple instance of database opened at the same time
        @Volatile
        private var INSTANCE : AppDatabase? = null
        fun getDataBase(context: Context): AppDatabase{
            val tempInstance = INSTANCE
            if(tempInstance != null) return tempInstance
            synchronized(this){
                val instance = Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "database-name").build()
                INSTANCE = instance
                return instance
            }
        }
    }
}

I dont understand why this is happening but I've a bigger project that needs this to works,so please any help is apprecited.

CodePudding user response:

I am using converters with GSON library without an issue, try it if that helps:

// Add this dependency to build.gradle(:app)
implementation 'com.squareup.retrofit2:converter-gson:2.8.1'
    @TypeConverter
    fun fromWoW(wow: WoW): String {
        return Gson().toJson(wow)
    }

    @TypeConverter
    fun toWoW(wowString: String): WoW {
        return Gson().fromJson(wowString, object : TypeToken<WoW>() {}.type)
    }
  • Related