Search code examples
androidandroid-room

how can create TypeConverter for RoomDatabase


in my project , I have two Data Model class first :

@Entity(tableName = TABLE_TASK)
data class TaskEntity(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "task_id")  val taskId: Int,
    @ColumnInfo(name = "task_title") val taskTitle: String?,
    @ColumnInfo(name = "task_desc") val taskDesc: String?,
    @ColumnInfo(name = "task_priority") val taskPriority: Int?,
    @ColumnInfo(name = "task_status") val taskStatus: String?,
    @ColumnInfo(name = "task_time") val taskTime: String?,
    @ColumnInfo(name = "task_notify") val taskNotify: String?
)

and second :

data class SubtaskModel(
    val subTasktitle : String?,
    val subTaskStatus : Boolean?
)

and I wanted to add a filed in my first Data Model class as the code below (the last field ) :

@Entity(tableName = TABLE_TASK)
data class TaskEntity(
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "task_id")  val taskId: Int,
    @ColumnInfo(name = "task_title") val taskTitle: String?,
    @ColumnInfo(name = "task_desc") val taskDesc: String?,
    @ColumnInfo(name = "task_priority") val taskPriority: Int?,
    @ColumnInfo(name = "task_status") val taskStatus: String?,
    @ColumnInfo(name = "task_time") val taskTime: String?,
    @ColumnInfo(name = "task_notify") val taskNotify: String?,
    @ColumnInfo(name = "task_subtask") val taskSubTask: MutableList<SubtaskModel>?
)

the error that i have got :

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

so I read(developer.android.com) and I did search about this but I couldn't figure out how can write Type Converter.

thank you


Solution

  • Follow below steps : 
    

    Step1. : create a convertor class -

         class MyConverter {
        
            @TypeConverter
            fun listToJson(value: List< SubtaskModel >?): String = Gson().toJson(value)
        
            @TypeConverter
            fun jsonToList(value: String) = Gson().fromJson(value, Array<SubtaskModel>::class.java).toList()
    }
    

    Step 2 -> Add converter to your dataBase class

    @Database(entities = [TaskEntity::class], version = 1)
    @TypeConverters(MyConverter::class)
    abstract class myDataBase : RoomDatabase() {
         abstract fun myDao(): MyDao
    }
    

    That's it.