Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of CursorLoaders?

Tags:

I use Cursors extensively in my app, to load and occasionally write information from and to a database. I have seen that Honeycomb and the Compatibility Package have new Loader classes designed to help with loading data in a "good" way.

Essentially, are these new classes (in particular CursorLoader) considerably better than previous methods of managing data? What is the benefit of a CursorLoader over managed Cursors for example?

And I use a ContentProvider to deal with data, which obviously takes Uris but how does this mesh with the initLoader() method? Must I set up each of my Fragments to use Loaders individually? And how unique does the id need to be for each loader, is it over the scope of my app or just a fragment? Is there any simple way of simply passing a Uri to a CursorLoader to query my data?

All I can see at the moment is that Loaders add an unnecessary extra step to getting my data into my app, so can someone explain them to me better?

like image 319
Alex Curran Avatar asked Aug 24 '11 22:08

Alex Curran


People also ask

How to use Loader in Android?

Loader API Summary There is only one LoaderManager per activity or fragment, but a LoaderManager can manage multiple loaders. To get LoaderManager, call getSupportLoaderManager() from the activity or fragment. To start loading data from a loader, call either initLoader() or restartLoader() .

What is a cursor loader?

A CursorLoader is a specialized member of Android's loader framework specifically designed to handle cursors. In a typical implementation, a CursorLoader uses a ContentProvider to run a query against a database, then returns the cursor produced from the ContentProvider back to an activity or fragment.

What are the characteristics of a loader?

Introduced in Android 3.0, loaders have these characteristics: They are available to every Activity and Fragment. They provide asynchronous loading of data in the background. They monitor the source of their data and automatically deliver new results when the content changes.


2 Answers

There are two key benefits to using a CursorLoader in your app over Activity.managedQuery():

  1. The query is handled on a background thread for you (courtesy of being build on AsyncTaskLoader) so large data queries do not block the UI. This is something the docs recommended you do for yourself when using a plain Cursor, but now it's done under the hood.
  2. CursorLoader is auto-updating. In addition to performing the initial query, the CursorLoader registers a ContentObserver with the dataset you requested and calls forceLoad() on itself when the data set changes. This results in you getting async callbacks anytime the data changes in order to update the view.

Each Loader instance is also handled through the singular LoaderManager, so you still don't have to manage the cursor directly, and now the connection can persist even beyond a single Activity. LoaderManager.initLoader() and LoaderManager.restartLoader() allow you to reconnect with an existing Loader already set up for your query and, in some cases, instantly get the latest data if it is available.

Your Activity or Fragment will likely now implement the LoaderManager.Callback interface. Calling initLoader() will result in the onCreateLoader() method where you will construct the query and a new CursorLoader instance, if necessary. The onLoadFinished() method will be fired each time new data is available, and will include the latest Cursor for you to attach to the view or otherwise iterate through.

In addition, there is a pretty good example of all this fitting together on the LoaderManager class documentation page: http://developer.android.com/reference/android/app/LoaderManager.html

like image 81
devunwired Avatar answered Nov 02 '22 22:11

devunwired


If anyone finds themselves in a similar situation, here's what I've done:

  • Created a class which implements LoaderCallbacks and handles all the queries you'll need.
  • Supply this with a Context and the Adapter in question.
  • Create unique IDs for each query you'll use (if you use a UriMatcher, might as well use the same ones)
  • Make a convenience method which transfers queries into the bundle required for the LoaderCallbacks
  • That's pretty much it :) I put some of my code below to show exactly what I did

In my GlobalCallbacks class:

public static final String PROJECTION = "projection"; public static final String SELECTION = "select"; public static final String SELECTARGS = "sargs"; public static final String SORT = "sort";  Context mContext; SimpleCursorAdapter mAdapter;  public GlobalCallbacks(Context context, SimpleCursorAdapter adapter) {     mContext = context;     mAdapter = adapter; }  @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) {      Uri contentUri = AbsProvider.customIntMatch(id);     if (contentUri != null) {         return new CursorLoader(mContext, contentUri, args.getStringArray(PROJECTION), args.getString(SELECTION),                  args.getStringArray(SELECTARGS), args.getString(SORT));     } else return null;  }  @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {     mAdapter.swapCursor(arg1);       }  @Override public void onLoaderReset(Loader<Cursor> arg0) {     mAdapter.swapCursor(null); } 

And when I wanted to use a CursorLoader (Helper.bundleArgs() is the convenience bundling method):

scAdapt = new Adapters.NewIndexedAdapter(mHost, getMenuType(),                  null, new String[] { "name" }, new int[] { android.R.id.text1 });         getLoaderManager().initLoader(                 GlobalCallbacks.GROUP,                 Helper.bundleArgs(new String[] { "_id", "name" }),                 new GlobalCallbacks(mHost, scAdapt));         setListAdapter(scAdapt); 

And in Helper:

public static Bundle bundleArgs(String[] projection, String selection, String[] selectionArgs) {     Bundle b = new Bundle();     b.putStringArray(GlobalCallbacks.PROJECTION, projection);     b.putString(GlobalCallbacks.SELECTION, selection);     b.putStringArray(GlobalCallbacks.SELECTARGS, selectionArgs);     return b; } 

Hope this helps someone else :)

EDIT

To explain more thoroughly:

  • First, an adapter with a null Cursor is initialised. We don't supply it with a Cursor because GlobalCallbacks will give the adapter the correct Cursor in onLoadFinished(..)
  • Next, we tell LoaderManager we want to initialise a new CursorLoader. We supply a new GlobalCallbacks instance (which implements Loader.Callbacks) which will then monitor the loading of the cursor. We have to supply it with the adapter too, so it can swap in the new Cursor once its done loading. At some point, the LoaderManager (which is built into the OS) will call onCreateLoader(..) of GlobalCallbacks and start asynchronously loading data
  • Helper.bundleArgs(..) just puts arguments for the query into a Bundle (e.g. columns projection, sort order, WHERE clause)
  • Then we set the Fragment's ListAdapter. The cursor will still be null at this point, so it will show a loading sign or empty message until onLoadFinished() is called
like image 31
Alex Curran Avatar answered Nov 03 '22 00:11

Alex Curran