Java – Search/filter ListViews by multiple criteria

Search/filter ListViews by multiple criteria… here is a solution to the problem.

Search/filter ListViews by multiple criteria

I currently have a layout with ListView and EditText widgets.
Objects in a ListView contain origin and destination.
EditText is used to filter departure locations.
I would like to add another EditText widget to be able to filter the list by origin and destination.
Any ideas how to add another filter class and filter ListView content by origin and then destination?

public class PlacesActivity extends Activity{
private EditText SearchText;
private RelativeLayout search;
private ImageButton btnSearchClose;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.places_layout);

SearchText = (EditText) findViewById(R.id.SearchBox);
SearchText.addTextChangedListener(filterTextWatcher);

btnSearchClose = (ImageButton)findViewById(R.id.SearchClose);
placesListView = (ListView) findViewById(R.id.PlacesListView);

}

private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
    adapter.getFilter().filter(s);
}

private final class MyFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence constraint) {
        FilterResults oReturn = new FilterResults();
        ArrayList<Routes> results = new ArrayList<Routes>();
        orig = routes;  
        }

if (constraint != null) {
            if (orig != null && orig.size() > 0) {
                for (Routes o : orig) {
                    String Constr = constraint.toString();
                    constraint = Constr.subSequence(0, Constr.length());

String FromRoute = o.getTripFrom().toLowerCase();
                    if (FromRoute.startsWith((String) constraint)) {
                        results.add(o);
                    }   
                }
                oReturn.values = results;
            }
        }
        return oReturn;
    }

@Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        ArrayList<Routes> objects = new ArrayList<Routes>();
        objects = (ArrayList<Routes>)results.values;
        routes = objects;
        notifyDataSetChanged();
    }
}

Solution

You need to write your own BaseAdapter to extend the Filterable. You can view the CursorAdapter (it is a Filterable but does not support changing/adding filters).

Cursor adapter
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.1_r1/android/widget/CursorAdapter.java#CursorAdapter

Related Problems and Solutions