deleting event from calendar in android programmatically

sesamoslu picture sesamoslu · Jun 11, 2013 · Viewed 8.4k times · Source

I have searched from the internet a lot and tried many examples . I can successfully add event to the calendar through my application but I can't delete this event programatically. Here are the samples I have tried that I cant end up a successful result .

tokens[1] is event id.
1)

  Uri eventsUri = Uri.parse(getCalendarUriBase()+"events");
  Uri eventUri = ContentUris.withAppendedId(eventsUri, Long.parseLong(tokens[1]));
  getContentResolver().delete(eventUri, null, null); 

2)

 ContentResolver cr = FlightOperationsCancelTicketFee.this.getContentResolver();
 Uri EVENTS_URI =    Uri.parse("content://com.android.calendar/" + "events");
 deleteEvent(cr, EVENTS_URI, 1);


 private void deleteEvent(ContentResolver resolver, Uri eventsUri, int calendarId) 
 {
     Cursor cursor;
     if (android.os.Build.VERSION.SDK_INT <= 7) 
     { 
         cursor = resolver.query(eventsUri, new String[]{ "_id" }, "Calendars_id=" + calendarId, null, null);
     } 
     else 
     { 
         cursor = resolver.query(eventsUri, new String[]{ "_id" }, "calendar_id=" + calendarId, null, null);
     }
     while(cursor.moveToNext()) 
     {
         long eventId = cursor.getLong(cursor.getColumnIndex("_id"));
         resolver.delete(ContentUris.withAppendedId(eventsUri, eventId), null, null);
     }
     cursor.close();
 }

3)

 ContentResolver cr = getContentResolver();
 String calUriString = "content://com.android.calendar/events";
 Uri cal=Uri.parse(calUriString);
 String[] EVENT_PROJECTION=new String[]{"calendar_id","title","dtstart","_id"};


 Uri eventsUri = Uri.parse(getCalendarUriBase()+"events");
 Uri eventUri =ContentUris.withAppendedId(eventsUri, Long.parseLong(tokens[1]));
 String reminderUriString = "content://com.android.calendar/reminders";
 Uri remUri =Uri.parse(reminderUriString);
     cr.delete(remUri, "event_id="+Commons.event_id, null);
 cr.delete(eventUri, null, null);

4)

   Uri eventsUri = Uri.parse(getCalendarUriBase()+"events");
   Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, Long.parseLong(tokens[1]));
   getContentResolver().delete(eventUri, null, null);

None of the above does work . I need help . Thank you .. Edit : I think I can't send the right context , is there a way to keep context via shared preferences ? However , it only keeps String and Int values . Is there another way to do something like this ?

Answer

Deepali-Systematix picture Deepali-Systematix · Dec 20, 2016

Use this code,It worked for me:

 Uri deleteUri = null;
        deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, Long.parseLong(String.valueOf(eventID)));
        int rows = getContentResolver().delete(deleteUri, null, null);
        Toast.makeText(this, "Event deleted", Toast.LENGTH_LONG).show();