Search code examples
androidkotlingsonandroid-room

How do i save the custome list in Room Db in Android Kotlin?


My model Class

@Entity(tableName = "Custome Tasks")
data class CustomeTask(
    @PrimaryKey(autoGenerate = true)
    val id: Long =  0,
    @NonNull
    val title: String,
    @NonNull
    @TypeConverters(DataConverter::class)
    val tasks: List<Task>
) 

Task data class

data class Task(
    val title : String ,
    val time : Int
)

Notice : i have one String and Int in Task Class. i think this is challenge . And i have used this typconverter by searching google

class DataConverter {


    @TypeConverter 
    fun fromOptionValuesList(tasks: 
       List<CustomeTask>?): String? {
        if (tasks == null) {
            return null
        }
        val gson = Gson()
        val type: Type = object :
            TypeToken<List<CustomeTask>?>() {}.type
        return gson.toJson(tasks, type)
    }

  @TypeConverter 
    fun toOptionValuesList(tasks: String?): List<CustomeTask>? {
        if (tasks == null) {
            return null
        }
        val gson = Gson()
        val type = object :
            TypeToken<List<CustomeTask>?>() {}.type
        return gson.fromJson(tasks, type)
  

  }
 }

I want to save that list of task in Table . How can do this.


Solution

  • Everything you have done is right except the class that you have passed in the DataConverter. You have passed CustomeTask class which is the Entity data class instead of the Task Class that is supposed to be passed. Simply update the model which is supposed to be converted from CustomeTask to Task Class in the DataConverter and you will be good to go.

    class DataConverter {
    
    
        @TypeConverter 
        fun fromOptionValuesList(tasks: 
           List<Task>?): String? {
            if (tasks == null) {
                return null
            }
            val gson = Gson()
            val type: Type = object :
                TypeToken<List<Task>?>() {}.type
            return gson.toJson(tasks, type)
        }
    
      @TypeConverter 
        fun toOptionValuesList(tasks: String?): List<Task>? {
            if (tasks == null) {
                return null
            }
            val gson = Gson()
            val type = object :
                TypeToken<List<Task>?>() {}.type
            return gson.fromJson(tasks, type)
      
    
      }
     }