sync event added programmatically with google calendar in android

15,853

Solution 1

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);
    }

Solution 2

Try this code to insert an event into the android calendar as well as google calendar:

 ContentValues values = new ContentValues();

   cal_id = String.valueOf(p1);
    values.put("calendar_id", p1);
    values.put("title", title1);
    values.put("allDay", 0);
    values.put("dtstart", settime); 
    values.put("dtend", cal.getTimeInMillis()+60*60*1000); 
    values.put("description", desc1);
    values.put("visibility", 0);
    values.put("transparency", 0);
    values.put("hasAttendeeData", 1);
    values.put("hasAlarm", 0);
    event = cr.insert(EVENTS_URI, values);
    event1=event; 
    dat1 = event.toString();
    long id=-1;
    if (event != null) 
    {
         id = Long.parseLong(event.getLastPathSegment());
         ContentValues values1 = new ContentValues();
         values1.put("event_id", id);
         values1.put("method", 1); //METHOD_ALERT

        Uri reminder = Uri.parse(getCalendarUriBase(this) + "reminders");
        this.getContentResolver().insert(reminder, values1);
        if(s.length() > 0 || partmail.length() > 0)
        {
     //REQUIRES FOLLOWING CODE 

This code is used to add the event sync'ed to the google calendar

             ContentValues attendees = new ContentValues();
             attendees.put("event_id", id);
             attendees.put("attendeeEmail", partmail1);
             attendees.put("attendeeRelationship", 2);//RELATIONSHIP_ATTENDEE
             attendees.put("attendeeStatus", 3); //ATTENDEE_STATUS_INVITED       
             attendees.put("attendeeType", 1); //TYPE_REQUIRED

            id1=(int)id;
            alarmid = (int) id;
            Uri attendeesUri = null;
            if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
            {
                     attendeesUri = Uri.parse("content://com.android.calendar/attendees");
            }
            else if(Integer.parseInt(Build.VERSION.SDK) < 8)
            {
                    attendeesUri = Uri.parse("content://calendar/attendees");
            }
            this.getContentResolver().insert(attendeesUri, attendees);

            Toast.makeText(this, "Task Scheduled Successfully", Toast.LENGTH_SHORT).show();
        }
        else
        {
            Toast.makeText(this, "Could not create Task!", Toast.LENGTH_SHORT);               
        }


    // reminder insert
    Uri REMINDERS_URI = Uri.parse(getCalendarUriBase(this) + "reminders");
    values = new ContentValues();
    values.put( "event_id", id);
    values.put( "method", 1 );
    values.put( "minutes", 0 );
    cr.insert( REMINDERS_URI, values );

Get Calendar's Uri since it differs for API levels such as till 8, greater than 8 and greater than 11.

private String getCalendarUriBase(Context con) {
String calendarUriBase = null;
Uri calendars = Uri.parse("content://calendar/calendars");
Cursor managedCursor = null;
try {
    managedCursor = managedQuery(calendars, null, null, null, null);
} catch (Exception e) {
    // eat
}

if (managedCursor != null) {
    calendarUriBase = "content://calendar/";
} else {
    calendars = Uri.parse("content://com.android.calendar/calendars");
    try {
        managedCursor = managedQuery(calendars, null, null, null, null);
    } catch (Exception e) {
        // statement to print the stacktrace
    }

    if (managedCursor != null) {
        calendarUriBase = "content://com.android.calendar/";
    }

}

return calendarUriBase;

}

Solution 3

Use the google calender api provided here

The above reference is somewhat general as Android doesn’t provide an official API. So, another solution more android specific is An Android Tutorial–Programming with Calendar

which contains a working example too. Also, be careful at Permission Declaration like READ_CALENDAR , WRITE_CALENDAR

Share:
15,853
user935143
Author by

user935143

Updated on June 16, 2022

Comments

  • user935143
    user935143 about 2 years

    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 !!!

  • asish
    asish about 12 years
    problem is not with adding event.The event has been added to the local calendar and showing as event of google calendar, But not in the google calendar.
  • Rethinavel
    Rethinavel over 5 years
    Can you add your getCalendarUri() function to the answer.