Android Filtering a List of Objects

13,593

Solution 1

    mFinalList will contain filtered data.

   List<Object> mFinalList=new ArrayList<>();


       for (Object person : listData) {
                if (person.getNameType().equalsIgnoreCase("somename")) {
                    mFinalList.add(person);
                } 

               }

        }

Solution 2

If your goal is to filter a list (List or ArrayList) on a simple constraint and diplay the datas in a ListView you can directly use the interface Filterable in your adapter as below :

public class AdapterFilterable extends BaseAdapter implements Filterable {

@Override
public Filter getFilter() {

    Filter filter = new Filter() {

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            if (results != null && results.values != null) {

                _arrayList = (List<object>) results.values;
            }
            else {
                _arrayList = ApplicationGlobal._dataManager.get_ArraylistFull();
            }
            notifyDataSetChanged();
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults results = new FilterResults();
            List<YourObject> filteredList = new ArrayList<YourObject>();

            //Do your filtering operation with the constraint String
            //Return result for publishResults to use it

            results.count = filteredList.size();
            results.values = filteredList;

            return results;
        }
    };
    return filter;
}

To use the filter, like when to search in a liste or just filter it with constraint you just need :

_yourAdapter.getFilter().filter(String yourConstraintString);

Else if you want to filter on complex datas you can certainly filter simply with a For loop and then do your notifyDataChanged();

hope it helps

Share:
13,593
James Oravec
Author by

James Oravec

I like egg rolls.

Updated on July 04, 2022

Comments

  • James Oravec
    James Oravec almost 2 years

    My question is similar to: java Best way to Filter list of object

    I have a list of objects say Sales. I want only the Sales objects whose Product matches the ones in another list, say saleProductList.

    Other than looping, is there a better way to do it.

    However I wish to be able to able to do the filtering with code accessible to android, e.g. The libraries would need to play nice with the android OS and run on the android OS. I'm hoping to avoid making home cooked code for a problem I assume is common, any suggestions?

  • afxentios
    afxentios over 7 years
    While this code may answer the question, it is better to include an explanation for the code to be easier understood.
  • James Oravec
    James Oravec over 7 years
    You'd want to do checks in your if statement to protect against possible NPEs.