How to run the query of a FilterQueryProvider asynchronously?

北城余情 提交于 2019-12-13 00:55:55

问题


I'm using a FilterQueryProvider to filter the 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.


回答1:


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




回答2:


According to CursorAdapter documentation you can use CursorAdapter#runQueryOnBackgroundThread



来源:https://stackoverflow.com/questions/7698795/how-to-run-the-query-of-a-filterqueryprovider-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!