简体   繁体   中英

Android Filtering a List of Objects

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, eg 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?

    mFinalList will contain filtered data.

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


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

               }

        }

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM