1

I'm trying to build a simple example application that counts the number of events on a specific calendar (I know the CALENDAR_DISPLAY_NAME of the Calendar) for today only.

I believe I need to query todays events with CalendarContract, and then count the number of rows in the cursor?

Is that correct? What would be the minimal, most efficient way to do the query on the single calendar, and have it return only the minimal possible set of data (event id only?) ?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
subsy
  • 11
  • 4

1 Answers1

0

This is the solution I arrived at:

First find the Calendar ID from the known name.

Then:

private Cursor getEventInstancesCursor() { // Query for a list of GQueues Calendar instances today

    // Set Calendar variable for start and end of today.
    Calendar startOfDay = Calendar.getInstance();
    int thisYear = startOfDay.get(Calendar.YEAR);
    int thisMonth = startOfDay.get(Calendar.MONTH);
    int thisDay = startOfDay.get(Calendar.DAY_OF_MONTH);
    startOfDay.set(thisYear, thisMonth, thisDay, 0, 0, 0);
    long startMillis = startOfDay.getTimeInMillis();
    Calendar endOfDay = Calendar.getInstance();
    endOfDay.set(thisYear, thisMonth, thisDay, 23, 59, 59);
    long endMillis = endOfDay.getTimeInMillis();

    long GQueuesCalID = getGQueuesCalID();
    Cursor eventsCursor = null;
    ContentResolver eventsCR = getContentResolver();

    String selection = CalendarContract.Instances.CALENDAR_ID + " = ?";
    String calIDString = String.valueOf(GQueuesCalID);
    String[] selectionArgs = {calIDString};

    try {
        return eventsCursor = eventsCR.query(
                CalendarContract.Instances.CONTENT_URI.buildUpon()
                        .appendPath(Long.toString(startMillis))
                        .appendPath(Long.toString(endMillis))
                        .build(),
                InstancesQuery.PROJECTION,
                selection,
                selectionArgs,
                null);

    } catch (Exception e) {
        Log.e(TAG, "Error querying calendar API", e);
        return null;
    }
}

Then just count the cursor rows.

subsy
  • 11
  • 4