Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Object Cursor

a-frank edited this page May 12, 2014 · 6 revisions

If you have queried data with a ContentResolver from a BaseContentProvider derived ContentProvider, you can convert the flattened data in the cursor to an ObjectCursor containing POJOs. For converting a normal Cursor into an ObjectCursor you can use the CursorUtil class.

GetAll

Get all Elements contained in the ObjectCursor. If the ObjectCursor is empty an empty Collection will be returned.

In this example we have two Entities: an Artist and an Album. One Album has exactly one Artist, but an Artist may have multiple Albums. Now we want to get all Albums of an Artist. First we construct the query and save it in a cursor. Then we convert this cursor into an ObjectCursor so we can retrieve POJOs. Finally we want a Collection containing all Albums of an Artist, so we get all objects in the ObjectCursor, close the cursor and return the Collection.

Cursor cursor = context.getContentResolver().query(BaseContentProvider.uri(DB.AlbumTable.TABLE_NAME), null, DB.AlbumTable.FK_ARTIST + "=?", new String[]{artists[0].getKey().toString()}, null);
ObjectCursor<Album> objects = CursorUtil.getObjectCursor(cursor);
Collection<Album> albums = objects.getAll();
cursor.close();
return albums;

GetCurrent

The ObjectCursor is providing all the normal move methods of an Android Cursor. This allows you to position the cursor just like you normally would. If you are in the position you want, you can get the current values as current object using the getCurrent method.

For example you want the second-last object. You move the Cursor to the correct position and get the object at this position:

Cursor cursor = context.getContentResolver().query(BaseContentProvider.uri(DB.AlbumTable.TABLE_NAME), null, DB.AlbumTable.FK_ARTIST + "=?", new String[]{artists[0].getKey().toString()}, null);
ObjectCursor<Album> objects = CursorUtil.getObjectCursor(cursor);
objects.moveToLast();
objects.moveToPrevious();
Album album = objects.getCurrent();
cursor.close();
return album;

Explore the JavaDoc for all available methods!