Search code examples
androidkotlinsearchview

Unchecked Cast warnning and ClassCastException


I have following code inside publishResults method where the containing adapter class implement Filterable interface to filter list of items. (objective: filtering items in a recycler view using a search view)

override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
  // taskList is of type MutableList<TaskItem>  
  taskList.clear()

  // crash on
  taskList.addAll(results!!.values as Collection<TaskItem>)

  notifyDataSetChanged()
}

app crashes with following error when tapped on search icon

java.lang.ClassCastException: android.widget.Filter$FilterResults cannot be cast to java.util.Collection

AS also shows following warning

Unchecked cast: Any! to Collection<TaskItem>

How to convert the taskList to a Collection without casting?


Update:

Added performFiltering method as @Andrei requested

override fun performFiltering(constraint: CharSequence?): FilterResults {

            val filteredList = ArrayList<TaskItem>()

            if(constraint == null || constraint.isEmpty()){
                filteredList.addAll(duplicatedTaskList)
            }
            else{
                val filterPattern: String = constraint.toString().toLowerCase().trim()

                for (taskItem in duplicatedTaskList){
                    if(taskItem.title.toLowerCase().contains(filterPattern))
                        filteredList.addAll(duplicatedTaskList)

                }
            }
            val filterResults = FilterResults()
            filterResults.values = filterResults

            return filterResults
        }

Solution

  • In your performFiltering method should be

    filterResults.values = filteredList
    

    instead of

    filterResults.values = filterResults
    

    Then your code with casting will works