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

TypeConverter not working for android Room DB

So I am trying to save a list of string pairs into my database but having some issues with the TypeConverter, I tried following guides ans other SO posts but can’t figure out whats wrong…

My Entity:

@Entity
data class Credential(
    @PrimaryKey()
    val id: String,

    @ColumnInfo(name = "name")
    val name: String,

    @ColumnInfo(name = "url")
    val url: String?,

    @TypeConverters(ListPairTypeConverter::class)
    @ColumnInfo(name = "fields")
    val fields: List<Pair<String, String>>
)

My Type Converter:

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

class ListPairTypeConverter {
    @TypeConverter
    fun storedStringToPairList(value: String): List<Pair<String, String>> {
        return value.split("~!!!!!~").map {
            val vals = it.split("!~~~~~!")
            Pair(vals[0], vals[1])
        }
    }

    @TypeConverter
    fun pairListToStoredString(pl: List<Pair<String, String>>): String {
        return pl.joinToString(separator = "~!!!!!~") { it.first + "!~~~~~!" + it.second }
    }
}

My Error:

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<kotlin.Pair<java.lang.String, java.lang.String>> fields = null;
                                                                                  ^

>Solution :

You are adding type converter at wrong place. instead of

@TypeConverters(ListPairTypeConverter::class)
@ColumnInfo(name = "fields")
val fields: List<Pair<String, String>>

You need to add at here

@Database(entities = [User::class], version = 1)
@TypeConverters(ListPairTypeConverter::class)
abstract class AppDatabase : RoomDatabase() {
  abstract fun userDao(): UserDao
}
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