Filtering with loadermanager and content provider

My snippet implements an interface LoaderManager.LoaderCallBacks<Cursor>to load a list view from a content provider using a custom cursor adapter. I use the SearchView widget to filter data in a list view, reloading the bootloader, as suggested by the http://developer.android.com/guide/components/loaders.html#restarting document .

I have two questions with this approach:

  • When I use restartLoader(), it gets called only onCreateLoader()then onLoadFinished(). I do not see the call onLoaderReset()in logcat. This means it is myadaptor.swapCursor(null)never executed during a search. Is the old cursor leaked exactly? Do I need to do myadaptor.swapCursor(null)before each call restartLoader()?

  • Is there a more efficient approach to filtering data? Because it seems too expensive to reload the entire bootloader for each character entered by the user. The Android source restartLoader()at http://androidxref.com/4.4.2_r2/xref/frameworks/base/core/java/android/app/LoaderManager.java#648 does a great job of tearing down the bootloader and recreating it. This would be more efficient if I could just fulfill the data request.

The 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);
}
+2
source share

Source: https://habr.com/ru/post/1793390/


All Articles