Here is my code for serachview and custom adapter. The function inside the custom adapter is not being called. No error but it is not working , nothin happen when i try to search in my list :
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(newText: String): Boolean {
if (TextUtils.isEmpty(newText)) {
// adapter?.filter
adapter?.filter("")
listView.clearTextFilter();
} else {
Log.i("searched ", newText)
adapter?.filter(newText);
}
return true;
}
override fun onQueryTextSubmit(query: String): Boolean {
// task HERE
return false
}
})
My custom adapter inner class inside a fragment :
inner class CustomAdapter(
private val context: Context,
private val ItemDataList: List<ContactEntity>
) : BaseAdapter() {
private val inflater: LayoutInflater =
this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getCount(): Int {
return ItemDataList.size
}
override fun getItem(position: Int): Int {
return position
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var contact = ItemDataList[position]
val rowView = inflater.inflate(R.layout.list_item_contact, parent, false)
rowView.findViewById<TextView>(R.id.customer_name).text = contact.name
rowView.tag = position
return rowView
}
// Filter Class
fun filterCustomer(charText: String) {
Log.i("searched inside:", charText)
var charText = charText
charText = charText.toLowerCase(Locale.getDefault())
mContacts = null
if (charText.isEmpty()) {
mContacts = ItemDataList
} else {
for (contact in ItemDataList) {
if (contact.name?.toLowerCase(Locale.getDefault())?.contains(charText)!!) {
mContacts = listOf(contact)
}
}
}
notifyDataSetChanged()
}
}
Here is my xml,I added searchview just above the listview :
<SearchView
android:id="@+id/searchView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<ListView
android:id="@+id/contact_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
My code was not working beacuse, I was not properly accessing the method of Custom adapter. The instance of adapter was null.
I changed this:
adapter?.filter(newText);
to that:
(listView.adapter as CustomAdapter?)?.filter(newText)
And it worked!