开发者

How to run the query of a FilterQueryProvider asynchronously?

I'm using a FilterQueryProvider to filter the 开发者_StackOverflow中文版content of a list view which is backed up by a custom CursorAdapter.

To use the FilterQueryProvider you have to override the runQuery() method which returns a Cursor object. Now I'm wondering how to query for the cursor asynchronously to avoid blocking the UI thread.

Is there some kind of best practice? I couldn't find any information whether the the runQuery() method is executed on the UI-thread or on its own thread.


From the documentation :

Filtering operations performed by calling filter(CharSequence, android.widget.Filter.FilterListener) are performed asynchronously

So your code should look like this :

private void filterList(CharSequence constraint) {
    final YourListCursorAdapter adapter = 
        (YourListCursorAdapter) getListAdapter();
    final Cursor oldCursor = adapter.getCursor();
    adapter.setFilterQueryProvider(filterQueryProvider);
    adapter.getFilter().filter(constraint, new FilterListener() {
        public void onFilterComplete(int count) {
            // assuming your activity manages the Cursor 
            stopManagingCursor(oldCursor);
            final Cursor newCursor = adapter.getCursor();
            startManagingCursor(newCursor);
            // safely close the oldCursor
            if (oldCursor != null && !oldCursor.isClosed()) {
                oldCursor.close();
            }
        }
    });
}

private FilterQueryProvider filterQueryProvider = new FilterQueryProvider() {
    public Cursor runQuery(CharSequence constraint) {
        return dbHelper.getListCursor(constraint);
    }
};

Sources : this and this


According to CursorAdapter documentation you can use CursorAdapter#runQueryOnBackgroundThread

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜