Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading all of today's events using CalendarContract - Android 4.0+

I'm trying to use Android's new calendar API to read all of today's calendar events. I'm have trouble finding the right selection on the database query to return all of the events. It seems that all recurring and all day events are left out of the selection. What selection args would permit me to obtain all of today's events from the calendar api?

Here is my current attempt:

    Cursor cur = null;
    String selection = "((" + CalendarContract.Events.DTSTART
            + " >= ?) AND (" + CalendarContract.Events.DTEND + " <= ?))";
    Time t = new Time();
    t.setToNow();
    String dtStart = Long.toString(t.toMillis(false));
    t.set(59, 59, 23, t.monthDay, t.month, t.year);
    String dtEnd = Long.toString(t.toMillis(false));
    String[] selectionArgs = new String[] { dtStart, dtEnd };
    cur = c.getContentResolver().query(CalendarContract.Events.CONTENT_URI,
            null, selection, selectionArgs, null);

I am unsure of how to broaden the selection or adding to it to get the recurring events and all day events. Any help would be appreciated.

like image 524
Zaid Daghestani Avatar asked Apr 13 '12 00:04

Zaid Daghestani


2 Answers

To get all events today, including recurring events, you need to use the Instances table, i.e.

Uri.Builder eventsUriBuilder = CalendarContract.Instances.CONTENT_URI
            .buildUpon();
ContentUris.appendId(eventsUriBuilder, timeNow);
ContentUris.appendId(eventsUriBuilder, endOfToday);
Uri eventsUri = eventsUriBuilder.build();
Cursor cursor = null;       
cursor = mContext.getContentResolver().query(eventsUri, columns, null, null, CalendarContract.Instances.DTSTART + " ASC");

Note that you must append the time constraints to the events uri, you cannot sort any other way.

In order to include all day events as well, just expand the the search to 11:59PM the previous night and 12:00AM tonight.

like image 126
Zaid Daghestani Avatar answered Nov 09 '22 14:11

Zaid Daghestani


Your conditions only give you the events that are strictly in today limits. You should check the ones that start before today and end after (multidays event).

For recurring events, I check them manually. I don't found another way.

I use something like:

String selection = "((" + CalendarContract.Events.DTSTART + " <= ?) AND (" + CalendarContract.Events.DTEND + " >= ?)) OR (" + CalendarContract.Events.RRULE + " is not null )";

String[] selectionArgs = new String[] { dtEnd, dtStart};

Regards,

like image 42
SebastienS Avatar answered Nov 09 '22 15:11

SebastienS