Home > OS >  Room Database: how to embedded a object model have ArrayList field?
Room Database: how to embedded a object model have ArrayList field?

Time:11-01

i have model like this

@Entity(tableName = "user_table")
class UserModel
    : Serializable {
    @PrimaryKey
    @NonNull
    var userId: String = ""

    @Embedded
    var location: LocationModel = LocationModel()
    ...
    }

    data class LocationModel(
        var city : String = "",
        var province : String = "",
        @TypeConverters(ConvertersDAO::class)
        var coordinates : ArrayList<Double> = ArrayList()
    )
}

and a ConvertersDAO class

class ConvertersDAO {
    @TypeConverter
    fun fromStringDouble(value: String?): ArrayList<Double>? {
        val listType: Type = object : TypeToken<ArrayList<Double>>() {}.type
        return Gson().fromJson(value, listType)
    }

    @TypeConverter
    fun fromArrayListDouble(list: ArrayList<Double>?): String? {
        val gson = Gson()
        return gson.toJson(list)
    }
}

but when i build app i get this error

error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
        private java.util.ArrayList<java.lang.Double> coordinates;

i try to put @TypeConverter on location but i still not work, what should i do? have a nice day, everyone!

CodePudding user response:

You could place @TypeConverters(ConvertersDAO::class) at:-

The @Database level (all Daos and Entities in that database will be able to use it.), e.g.

@Database(entities = [UserModel::class],version = 1)
@TypeConverters(ConvertersDAO::class)

at the @Entity level (all fields of the Entity will be able to use it) e.g.

@Entity(tableName = "user_table")
@TypeConverters(ConvertersDAO::class) 

and you should be able to code it at the @Entity's member/field level e.g.

@Embedded
@TypeConverters(ConvertersDAO::class)
var location: LocationModel = LocationModel()
  • all the above compile successfully when tested.

see https://developer.android.com/reference/androidx/room/TypeConverters

  • Related