Skip to content

Cannot update FilteredArrayAdapter #74

Open
@littlefyr

Description

@littlefyr

Ok, there is an odd assumption that goes into this abstract class.

Normally, you might simply plan to call adapter.add(newItem); adapter.notifyDataSetChanged(); but the constructors store the initial data list and then pass that each time to filter.

This assumes, then, that you update the list you used to create the adapter, before calling arrayadapter (or rather that you would call add on both the adapter and list).

This is HIGHLY counter intuitive and I couldn't find anything obvious that indicates this.

Since there is no getAllItems for the ArrayAdapter a couple of approaches come mind:

Overload the modification methods to update originalObjects:

  • void add(T object)
  • void addAll(Collection<? extends T> collection)
  • void addAll(T... items)
  • void clear()
  • int getCount()
  • T getItem(int position)
  • long getItemId(int position)
  • int getPosition(T item)
  • void insert(T object, int index)
  • void remove(T object)
  • void sort(Comparator<? super T> comparator)

Rebuild the List by calling adapter.getItem(pos) and pass that into the filter

Modify AppFilter.performFiltering() to loop through the array directly

protected FilterResults performFiltering(CharSequence chars) {
    FilterResults result = new FilterResults();
        ArrayList<T> keptObjects = new ArrayList<T>();
    if (chars != null && chars.length() > 0) {
        String mask = chars.toString();

        for(int i=0; i<adapter.getCount; i++) {
            T object = adapter.getItem(i);
            if (keepObject(object, mask)) {
                keptObjects.add(object);
            }
        }
    } else { 
        //Not ideal
        for(int i=0; i<adapter.getCount; i++) {
            T object = adapter.getItem(i);
            keptObjects.add(object);
        }
    }
    result.count = keptObjects.size();
    result.values = keptObjects;
    return result;
}

The last is not efficient if you expect to filtering on an empty string frequently.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions