I don't think that grabbing the cursor from loader.loadInBackground () is what you want. The loadInBackground () implementation basically executes the request and returns the cursor to the user interface thread, which is what you are trying to avoid.
Be careful anytime you expect in the user interface thread for the return value. This should be a good indicator that this is not what you want.
What I did to fix this problem was restart the bootloader. In my case, I am trying to use the action bar to search for my content. My class extends ListFragment and implements LoaderManager.LoaderCallbacks The activity that contains this implements OnQueryTextListener and calls the code that I do in the fragment in this fragment.
public void doSearch(String query) { Bundle bundle = new Bundle(); bundle.putString("query", query); getLoaderManager().restartLoader(LoaderMangerIdHelper.INVENTORY, bundle, this); }
Please note that you need to restart the bootloader. All loaders are controlled by the system. This will make your onCreateLoader receive the call again. So you will need to check the query string to establish your choice.
@Override public Loader<Cursor> onCreateLoader(int id, Bundle bundle) { String SELECTION = "someColumn=?"; List<String> selectionArgs = new ArrayList<String>(); selectionArgs.add("someArgs"); if (bundle != null && bundle.containsKey("query")) { SELECTION += " AND columnTitle LIKE ?"; selectionArgs.add(bundle.getString("query") + "%"); } final String[] SELECTION_ARGS = new String[selectionArgs.size()]; selectionArgs.toArray(SELECTION_ARGS); mLoader = new CursorLoader(getActivity(), RoamPay.Product.CONTENT_URI, null, SELECTION, SELECTION_ARGS, null); return mLoader; }
This will launch cursorLoading in the background. And the callbacks should be the same as usual.
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); // The list should now be shown. if (isResumed()) { setListShown(true); } else { setListShownNoAnimation(true); } } @Override public void onLoaderReset(Loader<Cursor> loader) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); }
source share