Add an event to your Android calendar

private void setEvent(){ long startMilis = 0; int mCalId = 1; long endMilis = 0; Calendar beginTime = Calendar.getInstance(); beginTime.set(2013, 1, 29, 9, 10); startMilis = beginTime.getTimeInMillis(); Calendar endTime = Calendar.getInstance(); endTime.set(2013, 1, 30, 10,10); endMilis = endTime.getTimeInMillis(); ContentResolver cr = getContentResolver(); ContentValues values = new ContentValues(); values.put(Events.CALENDAR_ID, mCalId); values.put(Events.DTSTART, startMilis); values.put(Events.DTEND, endMilis); values.put(Events.TITLE,"Special Event"); values.put(Events.DESCRIPTION, "Group Activity"); values.put(Events.EVENT_TIMEZONE, "America/Los_Angeles"); Uri uri = cr.insert(Events.CONTENT_URI, values); Toast.makeText(this, "Event Added", Toast.LENGTH_LONG).show(); } 

This is a snippet of my code where I want to add an event to the Android calendar. The code is working fine.

But when testing on the device, the specified event is not actually added or displayed on the calendar . The code is completely error free, and I have provided the necessary permissions.

Can someone please tell me exactly where I am doing wrong.

+4
source share
2 answers

If there are no errors, but, nevertheless, the event does not appear on the calendar, I suspect that the culprit is the appointment of mCalId = 1 .

A device can have multiple calendars. This does not guarantee that the first with id == 1 is the main one (and even if you used the main one, the user can have events in several different calendars - for example, personal and work).

So, it depends on what you want to do exactly. You must either:

  • use the main calendar (the one with IS_PRIMARY , but see the description below) or
  • first select a calendar (only if more than a few were found with the Calendar table query), and then use this calendar_id since then.
+3
source

You may be mistaken in Uri, I use this in my application:

  Uri EVENTS_URI = Uri.parse(CalendarContract.Events.CONTENT_URI.toString()); ContentResolver cr = getActivity().getContentResolver(); ContentValues values = new ContentValues(); values.put("calendar_id", 1); values.put(Events.TITLE, recordatorio); values.put(Events.ALL_DAY, 1); values.put(Events.EVENT_LOCATION, lugar); values.put("dtstart", calDate.getTimeInMillis()); values.put("dtend", calDate.getTimeInMillis()); values.put(Events.DESCRIPTION, observaciones); values.put("availability", 0); values.put(Events.HAS_ALARM, true); values.put(Events.EVENT_TIMEZONE, TimeZone.getDefault().toString()); Uri uri = cr.insert(EVENTS_URI, values); // to get the Id Event long eventID = Long.parseLong(uri.getLastPathSegment()); 
0
source

All Articles