Monday, September 26, 2011

Working with Android Cursors from ContentResolver

Ok, so this is just generally a matter of good programing technique, and not necessarily specific to Android, but it's a worth while demonstration of a pattern, and the way I implemented it.  I think it has another name, but I most recently encountered it in Ruby, where they call it "sandwich code."  Terrible name if you ask me.  But then I guess you didn't ask me.

Anyway, so you find yourself doing this same thing over and over again:

        

Cursor cursor = null ; 
 try {
  cursor = getContentResolver().query(uri, ...
  
  while (cursor.moveToNext()) {
   // do something specific here
  }
 } finally {
  if (cursor != null) {
   cursor.close();
  }
 }

 

It's this same bit of code, repeated all over the place in your application, but the only thing that is actually any different is the "do something specific" part.  Would be nice if we didn't have all that repetition, wouldn't it?

If Java had closures, it would be a lot easier. As it is, we can at least write an object oriented solution. To do that, I defined a class called FriendlyContentResolver. Ok, so that's a dumber name than "sandwich code."

Oh well. I was so deeply tempted to extend Android's ContentResolver that I did, in fact, extend ContentResolver...
public class FriendlyContentResolver extends ContentResolver { 

    // no default constructor for ContentResolver, so...
   public FriendlyContentResolver(Context context) {
        super(context);
   }



Whereupon I discovered that this was not such a simple thing to do. When you call the query method you get this exception:

Caused by: java.lang.AbstractMethodError: abstract method not implemented at android.content.ContentResolver.acquireProvider(ContentResolver.java) at android.content.ContentResolver.acquireProvider(ContentResolver.java:748) at android.content.ContentResolver.query(ContentResolver.java:256)

Ok, so I could have spent the time figuring out how to extend ContentResolver, but it probably wasn't worth it. So instead FriendlyContentResolver just delegates to the real ContentResolver, like this...
public class FriendlyContentResolver { 

 public FriendlyContentResolver(ContentResolver realResolver) {
  this.realResolver = realResolver;
 }

    ...

You then provide a version of the query method that takes a reference to a callback interface implementation, like this...
public void query(Uri uri, String[] projection, 
    String selection, 
    String[] selectionArgs, 
    String sortOrder, 
    RowHandler handler) {


Where the RowHandler is defined as...
 

interface RowHandler {
  public void onNextRow(Cursor cursor);
 }

As we'll see in a minute, the RowHandler.onNextRow method will be called once for each row in the result cursor. That's where all the specific work gets done.

RowHandler originally had a method called noResult that would get called if the query returned no results. But I never actually needed it. For all of my cases, it was enough to set a default and simply do nothing when there were no results of the query.

Now we can write the body of the query method that takes care of all of the cursor handling for you and lets you just write the row-handling code...
public void query(Uri uri, String[] projection, 
      String selection, 
      String[] selectionArgs, 
      String sortOrder, 
      RowHandler handler) {

 try {
  cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
  
  while (cursor.moveToNext()) {
   handler.onNextRow(cursor);
  }
 } finally {
  if (cursor != null) {
   cursor.close();
  }
 }
}

Obviously, you will want to put exception handling in your code, but I wanted to keep the clutter down.

Now, any time you want to make a query with the ContentResolver, all you have to do is this...
FriendlyContentResolver resolver = new FriendlyContentResolver(getContentResolver());
...
final Foo foo = null;

resolver.query(uri, projection, selection, selectionArs, null, 
 new RowHander(){
  @Override
  public void onNextRow(Cursor cursor) {
   String val = cursor.getString(0); // whatever...
   // do whatever you need to do here...
   foo = new Foo(val);
  });


This, of course, assumes the call is being made from an Activity. If it's not, just use the activity to get the ContentResolver instance and pass it along to where you need to instantiate the FriendlyContentResolver.
A potential problem you might encounter with this is when you need to set a value type local variable from inside your anonymous inner class (i.e., your RowHandler instance).

Let's say that foo is an int, rather than a Foo. There are multiple ways to handle this, but they're all basically the same: you create an object reference to hold your primitive type. The easiest way is to shove it in an array, like this...
FriendlyContentResolver resolver = new FriendlyContentResolver(getContentResolver());
...
final int[] foos = {0};

resolver.query(uri, projection, selection, selectionArs, null, 
 new RowHander(){
  @Override
  public void onNextRow(Cursor cursor) {
   String val = cursor.getString(0); // whatever...
   // do whatever you need to do here...
   foos[0] = new Foo(val);
  });

No comments:

Post a Comment