jerry jerry - 6 months ago 15
Android Question

Is an Android EVENT_ID Unique Across Calendars?

I am trying to manage calendar events in my app using Android's calendar provider. On the documentation page the following methods to delete an event and to open an event in the calendar are shown:

To delete an event:

private static final String DEBUG_TAG = "MyActivity";
...
long eventID = 201;
...
ContentResolver cr = getContentResolver();
ContentValues values = new ContentValues();
Uri deleteUri = null;
deleteUri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID);
int rows = getContentResolver().delete(deleteUri, null, null);
Log.i(DEBUG_TAG, "Rows deleted: " + rows);


To open a specific event in the calendar using calendar intent:

long eventID = 208;
...
Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, eventID);
Intent intent = new Intent(Intent.ACTION_VIEW)
.setData(uri);
startActivity(intent);


That works pretty well but I noticed that, different than in other transaction such as creating and retrieving events, the calendar id does not seem to be of significance. Why is that so? Can I safely assume that the system guarantees all event IDs to be unique across all calendars? Or could there be multiple events with the same ID, and what happens then?

Answer

Yes, that assumption is correct. The event ID you pass with the Uri maps directly to the row _id field, which is the primary key of the events table. So each event has a (system wide) unique id.

If you follow the calls of deleteEventsInternal in CalendarProvider2 you can see that the ID you passed is compared to the _id field of the events table.

The selection in line 3222 eventually evaluates to _id = <the ID you passed>

Regarding your question "Why is that so?":

The relationship between calendars and events is a one-to-many relationship, which means one calendar may contain multiple events, but one event belongs to exactly one calendar.

The way this is represented in the calendar database is the standard way of modeling this in relational databases, see http://www.databaseprimer.com/pages/relationship_1tox/

In database design this is also called the Second normal form.