Custom getFilter in custom ArrayAdapter in android

You are having problem, mainly because you are using custom object. If you pass a String or int value to array adapter its know how to filter it. But if you pass custom object default filter implementation have to no idea how to deal with that.

Although it is not clear what you are trying to do in your filter i recommend you following steps.

  1. Proper implementation of ListTO, although it has nothing to do with your goal right now
  2. Implement custom filter
  3. return your filter

Implement custom filter

First thing you have to do is, implements Filterable from your array adapter.

Second, provide implementation of your Filter

Filter myFilter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
         FilterResults filterResults = new FilterResults();   
         ArrayList<ListTO> tempList=new ArrayList<ListTO>();
         //constraint is the result from text you want to filter against. 
         //objects is your data set you will filter from
         if(constraint != null && objects!=null) {
             int length=objects.size();
             int i=0;
                while(i<length){
                    ListTO item=objects.get(i);
                    //do whatever you wanna do here
                    //adding result set output array     

                    tempList.add(item);

                    i++;
                }
                //following two lines is very important
                //as publish result can only take FilterResults objects
                filterResults.values = tempList;
                filterResults.count = tempList.size();
          }
          return filterResults;
      }

      @SuppressWarnings("unchecked")
      @Override
      protected void publishResults(CharSequence contraint, FilterResults results) {
          objects = (ArrayList<ListTO>) results.values;
          if (results.count > 0) {
           notifyDataSetChanged();
          } else {
              notifyDataSetInvalidated();
          }  
      }
     };

Last step,

@Override
     public Filter getFilter() {
        return myFilter;
    }

Leave a Comment