Tutorials‎ > ‎

Calendar

The calendar content provider is not officially published in the Android SDK but after searching through the Android source code I have finally figured out how to add events to calendars.
This tutorial only covers adding events to calendars. It does not cover reading events from calendars.

Before you can add an event to a calendar, you need to know which calendars exists and what their identifiers are.
Cursor cursor = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
cursor.moveToFirst();
String[] CalNames = new String[cursor.getCount()];
int[] CalIds = new int[cursor.getCount()];
for (int i = 0; i < CalNames.length; i++) {
    CalIds[i] = cursor.getInt(0);
    CalNames[i] = cursor.getString(1);
    cursor.moveToNext();
}
cursor.close();
The code above creates an array of strings containing the names and an array of integers containing the calendar_ids of all available calendars.

To actually add an event to a calendar, start by creating a ContentValues object.
Put a calendar_id from the array above in there along with the title, date and location for the event.
It should look something like this:
ContentValues cv = new ContentValues();
cv.put("calendar_id", CalIds[0]);
cv.put("title", myTitle);
cv.put("dtstart", startTime);
cv.put("dtend", endTime);
cv.put("eventLocation", myLocation);
Finally, write these values to the calendar like such:
cr.insert(Uri.parse("content://calendar/events"), cv);

As this content provider is not officially public, it could change in future Android versions which might break your app.