How can I delete event from calendar on android >= 8?

Viewed 76

I tried quite a few things, read a lot of SO posts about it but can't seem to. I want to delete all the events. Here is how I insert my calendar events:

                ContentResolver cr = Objects.requireNonNull(myContext.getContentResolver());
            ContentValues values = new ContentValues();
            values.put(CalendarContract.Events.DTSTART, myEventCalendar.getStartEvent());
            values.put(CalendarContract.Events.DTEND, myEventCalendar.getEndEvent());
            values.put(CalendarContract.Events.TITLE, myEventCalendar.getTitle());
            values.put(CalendarContract.Events.DESCRIPTION, myEventCalendar.getDescription());
            values.put(CalendarContract.Events.CALENDAR_ID, 1);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
            Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);

This method works great, but I can't seem to remove the events afterwards. Here is my code:

    @RequiresApi(api = Build.VERSION_CODES.O)
public void deleteEventCalendar(Context myContext) {
    Uri deleteUri = null;
    Cursor cursor = myContext.getContentResolver().query(CalendarContract.Calendars.CONTENT_URI, null, null, null, null);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(CalendarContract.Events._ID));
        deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id);
        myContext.getContentResolver().delete(deleteUri, null, null);
    }
    cursor.close();
}

}

I feel like I'm not that far but it's still impossible. Please help me.

1 Answers

The answer was in front of me from the start...

I was calling CalendarContract.Calendar and not CalendarContract.Event.

I was able to test this on different devices and everything works.

public void deleteEventCalendar(Context myContext) {
    Uri deleteUri = null;
    Cursor cursor = myContext.getContentResolver().query(CalendarContract.Events.CONTENT_URI, null, null, null, null);
    while (cursor.moveToNext()) {
        long id = cursor.getLong(cursor.getColumnIndexOrThrow(CalendarContract.Events._ID));
        deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, id);
        Log.i("id calendar","mon id"+id);
        myContext.getContentResolver().delete(deleteUri, null, null);
    }
    cursor.close();
}
Related