Development‎ > ‎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:
URI newevent = cr.insert(Uri.parse("content://calendar/events"), cv);

To add a reminder to the event you need to write a record to the events table.
In that record you must refer to the id of your new event which was returned by the insert method.
get the id like this:
String eventid = newevent.getPathSegments().get(newevent.getPathSegments().size()-1);
then make a new contentvalues object with these fields
cv.put("event_id",eventid);
cv.put("minutes",interval);
and insert into the reminders table
cr.insert(Uri.parse(content://calendar/reminders"),cv);

As this content provider is not officially public, it could change in future Android versions which might break your app.
Update: on Froyo the contentprovider uri has changed to "content://com.android.calendar/events"
thanks to Moamen for the new uri and reminder info

Comments