filtering with loadermanager and content provider

前提是你 提交于 2019-12-10 10:54:22

问题


My fragment implements the LoaderManager.LoaderCallBacks<Cursor> interface to load a list view from a content provider using a custom cursor adaptor. I use a SearchView widget to filter the data in the list view by restarting the loader as suggested by the doc http://developer.android.com/guide/components/loaders.html#restarting.

I have two questions with this approach :

  1. When I use restartLoader(), only the onCreateLoader() and then onLoadFinished() are called. I do not see a call to onLoaderReset() in the logcat. That means myadaptor.swapCursor(null) is never done during the search. So does the old cursor get leaked? Do i need to do myadaptor.swapCursor(null) before every call to restartLoader() ?

  2. Is there a more efficient approach to filter data? Because it seems way too expensive to restart the entire loader for every character entered by the user. The Android source of restartLoader() at http://androidxref.com/4.4.2_r2/xref/frameworks/base/core/java/android/app/LoaderManager.java#648 does a lot of work of tearing down the loader resources and recreating it. It would have been more efficient if i could just do a simple requery of the data.

Code :

searchView.setOnQueryTextListener(new OnQueryTextListener() {
    @Override
    public boolean onQueryTextChange(String query) {
        Bundle queryBundle = new Bundle();
        queryBundle.putString("SearchQuery", query);
        getLoaderManager().restartLoader(0, queryBundle, myFragment.this);
        return true;
    }
}


@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle queryBundle) {
    String selection = null;
    String[] selectionArgs = null;
    if(queryBundle != null){
        selection = myTable.COLUMN_ABC + " like ?";
        selectionArgs = new String[] {"%" + queryBundle.getString("SearchQuery") + "%"};
    }
    CursorLoader cursorLoader = new CursorLoader(getActivity(), uri, projection, selection, selectionArgs, null);
        return cursorLoader;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    myadaptor.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
    myadaptor.swapCursor(null);
}

来源:https://stackoverflow.com/questions/24344950/filtering-with-loadermanager-and-content-provider

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