Dim
Dim

Reputation: 4807

Room DB Array with constructor

I wish to use an boolean array (with specific size) in Room DB with constructor. How I initialize it and how to use it?

@Entity
data class RoleEntity(
@PrimaryKey(autoGenerate = true) var id: Long? = null,
@ColumnInfo(name = "title") var title: String?,
@ColumnInfo(name = "startTime") var startTime: Long?,
@ColumnInfo(name = "endTime") var endTime: Long?,
@ColumnInfo(name = "recurrence") var recurrence: BooleanArray,
@ColumnInfo(name = "priority") var priority: Int?
): Serializable {
constructor() : this(title = "", startTime = 0, endTime = 0, recurrence = ??, priority = 0)
}

Upvotes: 0

Views: 56

Answers (1)

For such attributes, it is necessary to use converters, and in your case, I will give my example, you will have it there by analogy.@Convert(converter = ListJsonConverter::class) var list: List<Map<String, Any>>, Also the converter itself

@Converter(autoApply = true)
class ListJsonConverter : AttributeConverter<List<Map<String, Any>>, String> {

private val objectMapper = ObjectMapper()

override fun convertToDatabaseColumn(attribute: List<Map<String, Any>>): String {
    return objectMapper.writeValueAsString(attribute)
}

override fun convertToEntityAttribute(dbData: String?): List<Map<String, Any>> {
    try {
        return dbData?.let { objectMapper.readValue<List<Map<String, Any>>>(it) } ?: emptyList()
    } catch (e: Exception){
        return emptyList()
    }
}

}

Here it is well written about them.

Upvotes: 1

Related Questions