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 class with 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>
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@SuppressWarnings("null")
@SuppressLint("DefaultLocale")
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults result = new FilterResults();
if (constraint != null && constraint.length() > 0) {
synchronized (this) {
mListSearch = new ArrayList<ContactsPojo>();
for (int i = 0; i < mListe.size(); i++) {
if ((mListe.get(i).getContactsName().toUpperCase())
.contains(constraint.toString()
.toUpperCase())) {
ContactsPojo contacts = new ContactsPojo();
contacts.setContactsName(mListe.get(i)
.getContactsName());
contacts.setImage(mListe.get(i).getImage());
mListSearch.add(contacts);
}
}
}
result.count = mListSearch.size();
result.values = mListSearch;
} else if (constraint == null && constraint.length() == 0) {
synchronized (this) {
result.count = mListe.size();
result.values = mListe;
}
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected void publishResults(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(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
mlistAdapter.getFilter().filter(s);
mlistAdapter.notifyDataSetChanged();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@SuppressLint("NewApi")
@Override
public void afterTextChanged(Editable s) {
if (s.toString().isEmpty()) {
mlistAdapter = new MyListAdapterTwoLine(_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"