Fetching Gmail Messages by Label on Android

Android has a nice setup for programmatically accessing data across applications called ContentProviders. There’s a content provider that you can use to read the email that Gmail has cached, but I was having a hard time finding an example of filtering by label. There’s a content::/gmail-ls/labels provider that returns summaries by labels. As you would expect the selection parameter to ContentResolver.query() is where you ask for a label. However, even though the docs for query() say that the selection parameter should be formatted as a SQL where clause this isn’t the case for content://gmail-ls. Format the query the same as you would for the Gmail search box.

Here’s an example of fetching the most recent unread messages for an account and writing out the subjects into a text buffer:

ContentResolver cr = getContentResolver();
Cursor unread = cr.query(Uri.parse("content://gmail-ls/conversations/xxxxxx@gmail.com"), null, "label:^u", null, null);
unread.moveToFirst();
int subjectIdx = unread.getColumnIndex("subject");
 
TextView tv = (TextView) findViewById(R.id.buffer);
do {
    String subject = unread.getString(subjectIdx);
    tv.append(subject + "\n");
} while (unread.moveToNext());
This entry was posted in Android, Community, Open Source, Technology, ThisIsMobility. Bookmark the permalink.

4 Responses to Fetching Gmail Messages by Label on Android

  1. js says:

    Thanks. Good posting.

  2. Raffaele says:

    Thanks a lot, it’s exactly the URI I was searching around for a while!!!

  3. Shree says:

    Does this still work? I thought Gmail blocked access to inbox recently?

  4. miker says:

    They may have now, I haven’t used this in quite a while.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">