Wednesday, August 10, 2011

Filtering Lists

I suppose for filtering a ListView that has only a single string in each item is probably pretty easy (haven't actually tried it yet). My first try required me to filter (as the user types on the keyboard) a ListView that is displaying several TextViews for each item.  Like this:


I had a hard time finding documentation on how to do this, and it took me a little while to figure it out.  There might well be a better way than this, but this is how I managed it.

The application is using a Cursor and SimpleCursorAdapter to get the data in the ListView.  All that I had to do was set the FilterQueryProvider to an anonymous inner class, in which the overridden runQuery method re-queries the database.  Like this:

  adapter.setFilterQueryProvider(new FilterQueryProvider() {

   @Override
   public Cursor runQuery(CharSequence startingWith) {
    try {
     Cursor newCur = dao.findByLastName(
       startingWith);
     startManagingCursor(newCur);
     return newCur;
     
    } catch (Exception ex) {
     // do something reasonable here
    }
    return cur; // original cursor if something went wrong.
   }
  });



No comments:

Post a Comment