0

I have an Error in my array adapter filter section. Everything works fine when I try to enter value in autocomplete textview app crash and show me following error.

java.lang.NullPointerException: null cannot be cast to non-null type java.util.ArrayList

following are my code

class ProductSearchAdapter(
    context: Context,
    private var list: ArrayList<SaleFilterListModel>
    ) : ArrayAdapter<SaleFilterListModel>(context, 0, list){

    @SuppressLint("ViewHolder")
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val binding = ProductSearchListBinding.inflate(LayoutInflater.from(context), parent, false)

        val item = list[position]
        binding.searchProductName.text = item.productName
        binding.searchProductRate.text = item.saleAmount
        return binding.root
    }

    override fun getFilter(): Filter {
        return productFilter

    }

    private val productFilter: Filter = object : Filter() {
        override fun performFiltering(constraint: CharSequence): FilterResults {
            val results = FilterResults()
            val suggestions = ArrayList<SaleFilterListModel>()
            if (constraint.isEmpty()) {
                suggestions.addAll(list)
            } else {
                val filterPattern = constraint.toString().lowercase().trim()
                for (item in list) {
                    if (item.productName.lowercase().contains(filterPattern)) {
                        suggestions.add(item)
                    }
                }
            }
            results.values = suggestions
            results.count = suggestions.size
            return results
        }

        override fun publishResults(constraint: CharSequence?, results: FilterResults?) {
            list = results?.values as ArrayList<SaleFilterListModel>
            notifyDataSetChanged()
        }

        override fun convertResultToString(resultValue: Any?): CharSequence {
            return (resultValue as SaleFilterListModel).productName
        }
    }

}
nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120
  • I don't use Filter, but try replacing that line with `list = (results.values as? ArrayList) ?: arrayListOf()` in case the problem is that it gives you null instead of an empty list when there are no result values. – Tenfour04 Jun 15 '21 at 19:06

1 Answers1

0

It is hard to tell without seeing the stack trace, but I would imagine that the publishResults function is the culprit here, as it is trying to cast what is a Nullable type (results?.values) to a Non-Nullable ArrayList<SaleFilterListModel>.

Certainly, this can be the case if publishResults is passed a null value for the results parameter.

nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120