sync event added programmatically with google calendar in android

user935143 picture user935143 · Jan 19, 2012 · Viewed 13.9k times · Source

I am trying to add an event to the android calendar, and I specify that the event will be added to the gmail calendar in order to sync with the Google calendar automatically. The problem is events added programmatically don't sync with Google calendar, but if I add it manual on the phone it does sync with Google calendar. I don't know why.

This is the code that I use to add the event:

ArrayList<MyCalendar> calendars = new ArrayList<MyCalendar>();

String[] projection = new String[] { "_id", "name" };
Uri calUri = getCalendarURI(false);
Cursor managedCursor = managedQuery(calUri, projection, "selected=1",
        null, null);

String calName = null;
String calId = null;
if (managedCursor.moveToFirst()) {

    int nameColumn = managedCursor.getColumnIndex("name");
    int idColumn = managedCursor.getColumnIndex("_id");
    do {
        calName = managedCursor.getString(nameColumn);
        calId = managedCursor.getString(idColumn);
        calendars.add(new MyCalendar(Integer.parseInt(calId), calName));
    } while (managedCursor.moveToNext());

}
Toast.makeText(getBaseContext(), calName + "  " + calId,
        Toast.LENGTH_LONG).show();

Calendar cal = Calendar.getInstance();
ContentValues event = new ContentValues();
event.put("calendar_id", 2);
event.put("title", "Test Event2");
event.put("description", "Hiii Buddy");
long startTime = cal.getTimeInMillis();
long endTime = cal.getTimeInMillis() + 60 * 60 * 1000;
event.put("dtstart", startTime);
event.put("dtend", endTime);
event.put("allDay", 0);
event.put("eventStatus", 1);// tentative 0, confirmed 1 canceled 2
event.put("visibility", 3);// default 0 confidential 1 private 2
                            // public 3
event.put("transparency", 0);// opaque 0 transparent 1
event.put("hasAlarm", 1); // 0 false, 1 true

Uri eventsUri = getCalendarURI(true);
Uri url = getContentResolver().insert(eventsUri, event);

So the event successfully added to calendar but it doesn't show up in the Google calendar at the web (don't sync) but if I add the event manually it does sync !!!

Answer

AliSh picture AliSh · Mar 28, 2014

You can sync your event after adding it by this function,It's worked for me(in API 8 and later):

public static void syncCalendar(Context context, String calendarId) {
        ContentResolver cr = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(CalendarContract.Calendars.SYNC_EVENTS, 1);
        values.put(CalendarContract.Calendars.VISIBLE, 1);

        cr.update(
                ContentUris.withAppendedId(getCalendarUri(),
                        Long.parseLong(calendarId)), values, null, null);
    }