tags:

views:

137

answers:

2

Hi all,

on android i have big listview which has to support filtering. For now my implementation is the following.

EditText and TextWatcher to listen for text changes. All data is stored in db and when there is event for TextChange fetch a cursor and set new CursorAdapter to the listview. I use AsyncTask to query the db and to update the gui.

But there comes some problems with this approach:

  1. AsyncTask is started for every TextChange event.

  2. The AsyncTask should be synchronized

So what is the best way to implement search field for a listview which elements are stored in db.

A: 

In your Activity, keep a static reference to the AsyncTask when you kick it off. Then, if the user types another key before the previous AsyncTask is complete, manually cancel it and kick off another one. That should alleviate most of the issues (although you might have some problems refreshing the list if it's a large data set). Something like the following should get you started:

private static AsyncTask _currentFilterTask;

public doFilter( String userInput )
{
  if ( _currentFilterTask != null && _currentFilterTask.getStatus().equals() )
  {
    _currentFilterTask.cancel( true );
  }
  _currentFilterTask = new MyAsyncTask( userInput );
  _currentFilterTask.execute( this ); 
}
Eric
A: 

Most of the Adapter implementations also implement Filterable interface which is very useful.

Filter filter = myAdapter.getFilter();
filter.filter(mySearchText);

According to the documentation Filter.filter(CharSequence constraint) does - Starts an asynchronous filtering operation. Calling this method cancels all previous non-executed filtering requests and posts a new filtering request that will be executed later. Which perfectly suits my needs.

Mojo Risin