Adapter / CursorAdapter / CursorLoader / Loader

Adapters – Part 5

Previously in this series we’ve looked at how to use Adapters in various ways, and how to keep the scrolling of our ListViews smooth. In this article, we’ll turn our attention to how to bind a ListView to data which is stored in a SQLite database.

As this series focuses on Adapters, I’m not going to provide a tutorial on SQLite databases and ContentProviders. For some useful information on these topics, please refer to Lars Vogel’s excellent tutorial. Grokking Android’s Wolfram Rittmeyer has also written some useful tutorials on this topic.

For our example, I have set up a simple database and ContentProvider. The database contains two columns: The obligatory ID column, and a column containing arbitrary text. We’ll simply store a set of numbers in text form (i.e. “One”, “Two”, “Three”, etc). To keep things simple, the database has been limited to the numbers 1-20. I won’t include this code in the article, but it’s available in the source if you want to look at it.

Before we dive in to the code, it’s worth looking at a fundamental shift in the recommended usage of CursorAdapters which occurred in API 11 Honeycomb 3.0. Prior to that the accepted usage was to use the FLAG_AUTO_REQUERY flag which would cause the Cursor to be re-retrieved when it detected a change to the database. The only problem with this is that the database queries are performed on the UI thread which can make your UI laggy or, in extreme cases, present the user with the dreaded “Application Not Responding” dialog. Looking at the Javadocs for CursorAdapter the suggestion is to use CursorLoader instead, but doesn’t give much more information. So we’ll implement things using a CursorLoader to see how to do this.

In actual fact, using a CursorLoader is simplicity itself, and it does a surprising amount for us. We used a Loader in the previous article, but this time we’ll implement our LoaderCallback in our ListFragment instead of in our ViewHolder as we don’t need a ViewHolder in this case:

In our onActivityCreated() method we kick off the Loader and it is in the onCreateLoader() method where we actually create our CursorLoader using some constants defined in the ContentProvider. We’re actually using the stock CursorLoader and we don’t have to subclass it because it actually does an awful lot for us, as we’ll explore in a while.

In our onLoadFinished() method we check whether a CursorAdapter already exists for the ListView and create one, if necessary. The Adapter that we’re using is a SimpleCursorAdapter which work in a similar way to the SimpleAdapter that we looked at in part 2 of this series. It allows us to map columns in our database to controls in the layout rather than the Map that we used in SimpleAdapter.

The remainder of the code is just adding a simple menu which adds a new item to the database which allows us to see quite what the relatively simple CursorLoader & Adapter are actually doing for us.

If we run this we’ll see an empty list, but if we click the add button a few times, we’ll see items automatically appear in the list:

CursorAdapter

None of the code that we’ve added detects the data changing, and the reason that it’s happening is because the CursorLoader does it for us. When we first ran the CursorLoader it registered a ContentObserver on the data so it is automatically run again (on a background thread, of course) whenever the data changes. You can see this happening if you set a breakpoint in the onLoadFinished() method and hit the “Add” button.

We also don’t need to worry about cleaning things up because the CursorLoader is tied to the Activity lifecycle so will be properly cleaned up when our Activity goes out of scope.

All in all we get a lot of functionality for just a few lines of code.

Apologies that this article has focused a little more on CursorLoader than CursorAdpater (and this is, after all a series on Adapters), but the Adapter itself is pretty straightforward if you already understand how SimpleAdapter works, and the implementation is made even easier when we use a CursorLoader instead of acquiring a Cursor directly from the ContentResolver. Of course the CursorLoader pattern is applicable wherever you use Cursors and is not limited solely to CursorAdapters.

In the next article we’ll have a look at how we use Adapters to populate ViewPagers.

The source code for this article is available here.

© 2013 – 2014, Mark Allison. All rights reserved.

CC BY-NC-SA 4.0 Adapters – Part 5 by Styling Android is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. Permissions beyond the scope of this license may be available at http://blog.stylingandroid.com/license-information.

4 Comments

  1. Don’t set CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER there is already an observer on CursorLaoder.

    With CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER you create a memory leak, you will see it with MAT after an orientation change …

  2. Fragments have their own LoaderManager (even for the Support one).
    Why are you doing :
    Activity activity = getActivity();
    if (activity instanceof FragmentActivity)
    {
    LoaderManager lm =
    ((FragmentActivity) activity)
    .getSupportLoaderManager();
    lm.restartLoader(0, null, this);
    }

    while you could do :
    LoaderManager im = getLoaderManager();
    im.restartLoader(0, null, this);

    Fabien

Leave a Reply

Your email address will not be published. Required fields are marked *