Search code examples
androidkotlinandroid-roomtypeconverter

storing Map in room database


I'm trying to store Map<String,String> in my Room database. So I created a Converter Class just like this:

class HashMapConverter {

    @TypeConverter
    fun toHashMap(value: JsonElement): Map<String, String> =
        Gson().fromJson(value, object : TypeToken<Map<String, String>>() {}.type)

    @TypeConverter
    fun fromHashMap(value: Map<String, String>): String =
        Gson().toJson(value)


}

and created my database class like this:

@Database(
    entities = [TasksModel::class],
    version = 1, exportSchema = false
)
@TypeConverters( HashMapConverter::class,EnumConverters::class)
abstract class TasksDatabase : RoomDatabase() {
    abstract val tasksDAO: TasksDAO
}

and this is my TaskModel:

@Entity(tableName = "Tasks")
data class TasksModel(
    @PrimaryKey
    @ColumnInfo
    val id: Int,

    @ColumnInfo
    val taskName: String,

    @ColumnInfo
    val date: Map<String, String>,

    @ColumnInfo
    val time: String?,

    @ColumnInfo
    val status: TaskStatus
)

I also have an Enum Converter class which works fine. but when I added HashMap to my database I get the error below:

Cannot figure out how to save this field into database. You can consider adding a type converter for it.
    private final java.util.Map<java.lang.String, java.lang.String> date = null;

what is wrong with that?


Solution

  • I believe that your issue is a little bit of a red herring. In that the issue is not with how to save the field but rather how to extract the field.

    You will have a String (as per the fromHashMap TypeConverter) stored in the database and the complaint/issue is that you are trying to extract that as a JsonElement in the toHashMap function.

    Try using :-

    @TypeConverter
    fun toHashMap(value: String): Map<String, String> = 
        Gson().fromJson(value, object : TypeToken<Map<String, String>>() {}.type)