Monday, 6 July 2015

Android add calendar event Programatically | Android Codes: Insertion and Deletion of Calendar Events | Configure email notification with Calendar app in Android

Hello Friends,
          Today, I am sharing my another android tutorial which covers following things:

1. Android- Adding events to calendar via your android application
2. Programmatically add reminder in android calendara
3. Configure email notification with Calendar app in Android


A. For adding event on Calendar

try {
 String eventUriString = "content://com.android.calendar/events";
 ContentValues eventValues = new ContentValues();
 eventValues.put("calendar_id", 1); // id, We need to choose from
     // our mobile for primary its 1
 eventValues.put("title", title);
 eventValues.put("description", desc);
 eventValues.put("eventLocation", place);

 long endDate = startDate + 1000 * 10 * 10; // For next 10min
 eventValues.put("dtstart", startDate);
 eventValues.put("dtend", endDate);

 // values.put("allDay", 1); //If it is bithday alarm or such
 // kind (which should remind me for whole day) 0 for false, 1
 // for true
  eventValues.put("eventStatus", status); // This information is
   // sufficient for most
   // entries tentative (0),
   // confirmed (1) or canceled
   // (2):
 eventValues.put("eventTimezone", "UTC/GMT +5:30");
 /*
  * Comment below visibility and transparency column to avoid
  * java.lang.IllegalArgumentException column visibility is invalid
  * error
  */
 // eventValues.put("allDay", 1);
 // eventValues.put("visibility", 0); // visibility to default (0),
   // confidential (1), private
   // (2), or public (3):
   // eventValues.put("transparency", 0); // You can control whether
   // an event consumes time
   // opaque (0) or transparent
   // (1).
 eventValues.put("hasAlarm", 1); // 0 for false, 1 for true

 Uri eventUri = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(Uri.parse(eventUriString), eventValues);
 eventID = Long.parseLong(eventUri.getLastPathSegment()); 
} catch (Exception ex) {
 log.error("Error in adding event on calendar" + ex.getMessage());
}


B. Set Reminder for above added event id:

if (needReminder) {
/***************** Event: Reminder(with alert) Adding reminder to event *******************/
        String reminderUriString = "content://com.android.calendar/reminders";
 ContentValues reminderValues = new ContentValues();
 reminderValues.put("event_id", eventID);
 reminderValues.put("minutes", 5); // Default value 
       //set time in min which occur before event start   
 reminderValues.put("method", 1); // Alert Methods: Default(0),
     // Alert(1), Email(2),SMS(3)
 Uri reminderUri = curActivity.getApplicationContext()
      .getContentResolver()
    .insert(Uri.parse(reminderUriString), reminderValues);
}
 

C: Send mail to user for attending the meeting added on calendar

/***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/

if (needMailService) {
 String attendeuesesUriString = "content://com.android.calendar/attendees";

 /********
  * To add multiple attendees need to insert ContentValues
  * multiple times
  ***********/
 ContentValues attendeesValues = new ContentValues();
 attendeesValues.put("event_id", eventID);
 attendeesValues.put("attendeeName", "xxxxx"); // Attendees name
 attendeesValues.put("attendeeEmail", "yyyy@gmail.com");// Attendee email
 attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1),
       // Relationship_None(0),
       // Organizer(2),
       // Performer(3),
       // Speaker(4)
 attendeesValues.put("attendeeType", 0); // None(0), Optional(1),
      // Required(2),
      // Resource(3)
 attendeesValues.put("attendeeStatus", 0); // NOne(0),
          // Accepted(1),
        // Decline(2),
        // Invited(3),
        // Tentative(4)

 Uri eventsUri = Uri.parse("content://calendar/events");
 Uri url = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(eventsUri, attendeesValues);

 // Uri attendeuesesUri = curActivity.getApplicationContext()
    // .getContentResolver()
    // .insert(Uri.parse(attendeuesesUriString), attendeesValues);
} 

D: For deletion of calendar event: Here "id" is event id.

Uri uri = ContentUris.withAppendedId(CALENDAR_URI, Integer.parseInt(id));
getContentResolver().delete(uri, null, null); 

Finally All together: Add this method in your activity class

public long addAppointmentsToCalender(Activity curActivity, String title,
   String desc, String place, int status, long startDate,
   boolean needReminder, boolean needMailService) {
/***************** Event: add event *******************/
long eventID = -1;
try {
        String eventUriString = "content://com.android.calendar/events";
 ContentValues eventValues = new ContentValues();
 eventValues.put("calendar_id", 1); // id, We need to choose from
              // our mobile for primary its 1
 eventValues.put("title", title);
 eventValues.put("description", desc);
 eventValues.put("eventLocation", place);

 long endDate = startDate + 1000 * 10 * 10; // For next 10min
 eventValues.put("dtstart", startDate);
 eventValues.put("dtend", endDate);

 // values.put("allDay", 1); //If it is bithday alarm or such
   // kind (which should remind me for whole day) 0 for false, 1
   // for true
 eventValues.put("eventStatus", status); // This information is
   // sufficient for most
   // entries tentative (0),
   // confirmed (1) or canceled
   // (2):
 eventValues.put("eventTimezone", "UTC/GMT +5:30");
 /*
  * Comment below visibility and transparency column to avoid
  * java.lang.IllegalArgumentException column visibility is invalid
  * error
  */
 // eventValues.put("allDay", 1);
 // eventValues.put("visibility", 0); // visibility to default (0),
                                      // confidential (1), private
                                      // (2), or public (3):
 // eventValues.put("transparency", 0); // You can control whether
                                        // an event consumes time
                          // opaque (0) or transparent (1).
   
        eventValues.put("hasAlarm", 1); // 0 for false, 1 for true

 Uri eventUri = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(Uri.parse(eventUriString), eventValues);
 eventID = Long.parseLong(eventUri.getLastPathSegment());

 if (needReminder) {
 /***************** Event: Reminder(with alert) Adding reminder to event ***********        ********/
 
        String reminderUriString = "content://com.android.calendar/reminders";
        ContentValues reminderValues = new ContentValues();
 reminderValues.put("event_id", eventID);
 reminderValues.put("minutes", 5); // Default value of the
       // system. Minutes is a integer
 reminderValues.put("method", 1); // Alert Methods: Default(0),
     // Alert(1), Email(2),SMS(3)

 Uri reminderUri = curActivity.getApplicationContext()
     .getContentResolver()
     .insert(Uri.parse(reminderUriString), reminderValues);
 }

/***************** Event: Meeting(without alert) Adding Attendies to the meeting *******************/

 if (needMailService) {
 String attendeuesesUriString = "content://com.android.calendar/attendees";
 /********
  * To add multiple attendees need to insert ContentValues
  * multiple times
  ***********/
 ContentValues attendeesValues = new ContentValues();
 attendeesValues.put("event_id", eventID);
 attendeesValues.put("attendeeName", "xxxxx"); // Attendees name
 attendeesValues.put("attendeeEmail", "yyyy@gmail.com");// Attendee Email
 attendeesValues.put("attendeeRelationship", 0); // Relationship_Attendee(1),
       // Relationship_None(0),
       // Organizer(2),
       // Performer(3),
       // Speaker(4)
 attendeesValues.put("attendeeType", 0); // None(0), Optional(1),
      // Required(2),
      // Resource(3)
 attendeesValues.put("attendeeStatus", 0); // NOne(0),
        // Accepted(1),
        // Decline(2),
        // Invited(3),
        // Tentative(4)

 Uri eventsUri = Uri.parse("content://calendar/events");
 Uri url = curActivity.getApplicationContext()
    .getContentResolver()
    .insert(eventsUri, attendeesValues);

 // Uri attendeuesesUri = curActivity.getApplicationContext()
    // .getContentResolver()
    // .insert(Uri.parse(attendeuesesUriString), attendeesValues);
 }
} catch (Exception ex) {
 log.error("Error in adding event on calendar" + ex.getMessage());
}

return eventID;

}
 

Also need to add following permission in your AndroidManifest.xml file

<uses-permission android:name="android.permission.READ_CALENDAR" />
<uses-permission android:name="android.permission.WRITE_CALENDAR" />


Hope this will help some one.

Enjoy Coding :)

Mukesh Yadav

Hi Guys I am from Delhi working as Web/Mobile Application Developer(Android Developer), also have knowledge of Roboelctric and Mockito ,android test driven development... Blogging has been my passion and I think blogging is one of the powerful medium to share knowledge and ideas....

11 comments:

  1. thanks for the guide but if possible, can you upload the full code of them including the layout?

    ReplyDelete
  2. Can i get entire code plz?plz send to reena@maksinfotech.com

    ReplyDelete
  3. Hello,
    I have provided the call which you just need to bind with your ui. If you still
    face the issue then drop me your sample code and I will check and fix it.
    My id is : himky02@gmail.com.

    ReplyDelete
  4. Hi Mukesh,

    I am trying to build a custom calendar for events.
    Read,delete,update and show specific event list.

    Till now my code is working fine to read calendar events and display the same. but i am not able to integrate your given code to add event ....
    Can you please help me...

    I am using a Tab layout in my app. One tab is EVENT tab Onclick of event tab I am displaying event calendar and on button click trying to Add events....

    TO read and display calendar events I referred below link
    http://www.androiddevelopersolutions.com/2013/05/android-calendar-sync.html

    ReplyDelete
  5. Hi Mukesh,

    I am trying to build a custom calendar for events.
    Read,delete,update and show specific event list.

    Till now my code is working fine to read calendar events and display the same. but i am not able to integrate your given code to add event ....
    Can you please help me...

    I am using a Tab layout in my app. One tab is EVENT tab Onclick of event tab I am displaying event calendar and on button click trying to Add events....

    TO read and display calendar events I referred below link
    http://www.androiddevelopersolutions.com/2013/05/android-calendar-sync.html

    ReplyDelete
  6. Hi Mukesh,

    I am trying to build a custom calendar to display events.
    Functions - Add event,Delete,remainders,update,display event event..

    Till now my code working fine for custom calendar and display calendar events but i am not able to integrate your above code whenever i am trying to integrate my app stopped unfortunately.


    In my project i am using tab layout...one of my tab is Event tab and using fragments I am trying to display custom calendar .. i need to add event on button click..


    Can you please help me .....

    I referred the custom calendar and display event code from below link :
    http://www.androiddevelopersolutions.com/2013/05/android-calendar-sync.html

    ReplyDelete
  7. Hi mukesh, i am getting this error when i click date which has an event:
    java.lang.IndexOutOfBoundsException: Invalid index 46, size is 12

    ReplyDelete
  8. Im having trouble implementing your codes on my code

    ReplyDelete
  9. Can i get entire code.
    plz send it to srinivasannamachivayan@gmail.com

    ReplyDelete
  10. how can i get a current time event in my application

    ReplyDelete
  11. hi how can a show notification from my custom calendar when particular events occur

    ex: if i added event for tomarrow at 1pm it my app should throw notification at tmrw 1pm plz help me

    ReplyDelete

 

Copyright @ 2013 Android Developer Blog.

Blog Widget by LinkWithin