I am a begginer in Android but I tried to make a custom listview filtering and I it worked somehow. The only problem I have is that the ArrayList that I kept all the values
Your problem are this lines:
this.original = items;
this.fitems = items;
Items is the list you use for your ListView and putting it in two different variables does not make two different lists out of it. You are only giving the list items two different names.
You can use:
this.fitems = new ArrayList(items);
that should generate a new List and changes on this list will only change the fitems list.
you can accomplish the same effect by just creating a toString()
method on your Pkmn class that returns the value you want to filter by.
The best way I found to to filter ArrayAdapter is to create my own filter class:
private class MyFilter extends Filter
then in that function create the new object array to display after the filter (you can find good implementation in the source code of class ArrayAdapter
)
@Override
protected FilterResults performFiltering(CharSequence prefix)
now the trick is in this method
@Override
protected void publishResults(CharSequence constraint, FilterResults results)
when you use the Array adapter you can't do this:
myAdapterData = results.values
since then you disconnect your data from the super data, you must do this to keep your reference to the super original data array:
data.clear();
data.addAll((List<YourType>) results.values);
and then override
getFilter()
in your adapter, for example:
@Override
public Filter getFilter() {
if (filter == null) {
filter = new MyFilter();
}
return filter;
}
They have it covered here: https://www.mysamplecode.com/2012/07/android-listview-custom-layout-filter.html
You'll need to call clear() on the arrrat adapter to not hit the indexBoundException and add() on every element, since addAll() is valid only since honeycomb.
@SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) {
countryList = (ArrayList<Country>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = countryList.size(); i < l; i++)
add(countryList.get(i));
notifyDataSetInvalidated();
}