Sunday, March 6, 2011

Android: Working with Sqlite Cursors & Queries

If you're like me you learn to code by example.  One of the things I was having trouble with was selecting data from sqlite.  Not that I couldn't figure out how to get all the data, but how could I get just the data I needed.

The generic getContentResolver.query(Groups.CONTENT_URI, null, null, null, null); just seemed wasteful.  Here's what I've gleaned from other posts around the internet and from the SDK documentation:


ContentResolver cr = getContentResolver();
        Cursor groupCur = cr.query(
                Groups.CONTENT_URI, // what table/content
                new String [] {Groups._ID, Groups.NAME},    // what columns
                "Groups.NAME NOT LIKE + 'System Group:%'", // where clause(s)
                null, // ???
                Groups.NAME + " ASC" // sort order
        );

Further, if you want to just get a single row by it's _ID you can do this:

ContentResolver cr = getContentResolver();
        Uri myGroup = Uri.withAppendedPath(Groups.CONTENT_URI, "16");
        Cursor groupCur = cr.query(myGroup, new String [] {Groups._ID, Groups.NAME}, null, null, null);

Hope this is helpful and saves you some grief ;)

1 comment:

  1. hi
    thanks for the example.
    I am a novice with androidDB and I have a question:
    what does it means the 'null' fields?
    thanks!!

    ReplyDelete