Search code examples
javaandroidkotlinandroid-roomandroid-architecture-components

Room - Compare lists in Entity


I have a problem with Room. I have an Entity:

@Entity(tableName = "Entity")
data class Entity(val recipients: List<ID>?) {
    @ColumnInfo(name = "id")
    @PrimaryKey(autoGenerate = true) var id: Long = 0
}

As you can see it holds List of ID's (typealias ID = Long) And so, I made TypeConverter:

@TypeConverter
fun getListOfLongs(data: String?): List<ID> {
    if (data == null) {
        return Collections.emptyList()
    }
    val listType = object : TypeToken<List<Long>>() {}.type

    return gson.fromJson(data, listType)
}

@TypeConverter
fun convertListToString(ids: List<ID>): String = gson.toJson(ids)

But I have a problem, I can't make right Query for this list:

@Query("select count(*) from Message where recipients in (:recipients)")
fun count(recipients: List<ID>?): Int

As you see, I need to compare two lists (list in entity and list from method) and get all entities which contains Id's from method's list, but this Query returns always 0. I read that with TypeConverter's lists may be problems, but I can't find any solution.


Solution

  • Solve it with @RawQuery:

    " WHERE recipients LIKE ${recipients.joinToString(",", "\"", "\"")}"
    

    end editing TypeConvertor:

    @TypeConverter
    fun getListOfLongs(data: String?): List<Long> {
        if (data == null) {
            return Collections.emptyList()
        }
        val listType = object : TypeToken<List<Long>>() {}.type
    
        return gson.fromJson("[$data]", listType)
    }
    
    @TypeConverter
    fun convertListToString(ids: List<Long>?): String? {
        if (ids == null) return null
        var idsString = gson.toJson(ids)
        idsString = idsString.replace("]", "")
        idsString = idsString.replace("[", "")
        return idsString
    }