Android Listview With Custom Adapter Search Not Working
I am trying to apply search on ndroid ListView but its not working for me, here is the code i have tried. final ArrayList uData = new ArrayList(); listVi
Solution 1:
The Adapter you are using not works with Filter. It only works with ArrayAdapter. So either you use ArrayAdapter or write your own code for filteration of data.
Solution 2:
You may follow below step:
1) Implements your Base adapter classwith filterable class
2) You will get overriden method "public Filter getFilter()" you can use below code for filtering data
mListe is the original ArrayList<ContactsPojo>
mListSearch is the filtered ArrayList<ContactsPojo>
@Overridepublic Filter getFilter() {
Filterfilter=newFilter() {
@SuppressWarnings("null")@SuppressLint("DefaultLocale")@Overrideprotected FilterResults performFiltering(CharSequence constraint) {
FilterResultsresult=newFilterResults();
if (constraint != null && constraint.length() > 0) {
synchronized (this) {
mListSearch = newArrayList<ContactsPojo>();
for (inti=0; i < mListe.size(); i++) {
if ((mListe.get(i).getContactsName().toUpperCase())
.contains(constraint.toString()
.toUpperCase())) {
ContactsPojocontacts=newContactsPojo();
contacts.setContactsName(mListe.get(i)
.getContactsName());
contacts.setImage(mListe.get(i).getImage());
mListSearch.add(contacts);
}
}
}
result.count = mListSearch.size();
result.values = mListSearch;
} elseif (constraint == null && constraint.length() == 0) {
synchronized (this) {
result.count = mListe.size();
result.values = mListe;
}
}
return result;
}
@SuppressWarnings("unchecked")@OverrideprotectedvoidpublishResults(CharSequence constraint,
FilterResults result) {
if (result.count == 0) {
// mListe = (ArrayList<ContactsPojo>) mListe;
notifyDataSetInvalidated();
} else {
mListe = (ArrayList<ContactsPojo>) result.values;
notifyDataSetChanged();
}
}
};
return filter;
}
3) Then you can add this filter to edittext
edtSearchContacts.addTextChangedListener(newTextWatcher() {
@OverridepublicvoidonTextChanged(CharSequence s, int start, int before,
int count) {
mlistAdapter.getFilter().filter(s);
mlistAdapter.notifyDataSetChanged();
}
@OverridepublicvoidbeforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@SuppressLint("NewApi")@OverridepublicvoidafterTextChanged(Editable s) {
if (s.toString().isEmpty()) {
mlistAdapter = newMyListAdapterTwoLine(_con, al3);
lvPhnContacts.setAdapter(mlistAdapter);
}
}
});
}
In afterTextChanged method you will get original items back to listview.
Solution 3:
You can't convert BaseAdapter
to Filterable
. Beacause BaseAdapter
not implemented Filterable
. Try using SimpleAdapter
.
Post a Comment for "Android Listview With Custom Adapter Search Not Working"