Home > Blockchain >  Filter on list by a generic column in Kotlin Android
Filter on list by a generic column in Kotlin Android

Time:02-04

I am using Kotlin and trying to filter on a generic class, therefore I don't actually have the name to go after the it.__ Is there a way of filtering on a generic column name ? Using map{columnName} actually works, but I want the whole table, not just that column returned.

override fun getData(
    tableName: String,
    searchTerm: String?,
    columnName: String?
): List<BaseEntity> {
    for (clazz in getAllEntityClasses()) {
        if (clazz.simpleName == tableName) {
            val list = getList()
            return list.filter{it.GENERIC_COLUMNAME == searchTerm} as List<BaseEntity>
                }
            
            }
    
    return listOf()
}

CodePudding user response:

If I understand correctly you want to filter the list based on the value of a field of the objects in the list. If the column name is the same as the field name then you can do something like this:

override fun getData(
    tableName: String,
    searchTerm: String?,
    columnName: String?
): List<BaseEntity> {
    for (clazz in getAllEntityClasses()) {
        if (clazz.simpleName == tableName) {
            val list = getList()
            val field = clazz.getDeclaredField(columnName)
            field.isAccessible = true
            return list.filter{field.get(it) == searchTerm} as List<BaseEntity>                    
        }
    }
    return listOf()
}

Note that it is necessary to make the field accessible otherwise private fields will throw an error.

  •  Tags:  
  • Related