Friday, 5 August 2011

Adding Event to Calendar

Let's add events to calendar:

ContentResolver cr = getContentResolver();
       
//Find out which calendars exist...
Cursor cursor_calendar; // = cr.query(Uri.parse("content://com.android.calendar/calendars"), new String[]{ "_id",  "displayname" }, null, null, null);
if (Integer.parseInt(Build.VERSION.SDK) >= 8 ){
    cursor_calendar = cr.query(Uri.parse("content://com.android.calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
}
else{
    cursor_calendar = cr.query(Uri.parse("content://calendar/calendars"), new String[]{ "_id", "displayname" }, null, null, null);
}

cursor_calendar.moveToFirst();
String[] CalNamess = new String[cursor_calendar.getCount()];
int[] CalIdss = new int[cursor_calendar.getCount()];
for (int i = 0; i < CalNamess.length; i++) {
    CalIdss[i] = cursor_calendar.getInt(0);
    CalNamess[i] = cursor_calendar.getString(1);
    cursor_calendar.moveToNext();
}
cursor_calendar.close();

//Call this function to add event...
private void addEventToCalendar(int calender_id, String title, long start_date, long end_date){
   
    ContentValues cv = new ContentValues();
    cv.put("calendar_id", calender_id);
    cv.put("title", title);
    cv.put("dtstart", start_date );
    cv.put("hasAlarm", 1);
    cv.put("dtend", end_date);

    Uri newEvent ;
    if (Integer.parseInt(Build.VERSION.SDK) >= 8 ){
        newEvent = cr.insert(Uri.parse("content://com.android.calendar/events"), cv);
    }   
    else{
        newEvent = cr.insert(Uri.parse("content://calendar/events"), cv);
    }   

    if (newEvent != null)
    {
        long id = Long.parseLong( newEvent.getLastPathSegment() );
        ContentValues values = new ContentValues();
        values.put( "event_id", id );
        values.put( "method", 1 );
        values.put( "minutes", 0 ); // 15 minut Before
        if (Integer.parseInt(Build.VERSION.SDK) >= 8 )
            cr.insert( Uri.parse( "content://com.android.calendar/reminders" ), values );
        else
            cr.insert( Uri.parse( "content://calendar/reminders" ), values );
    }
}

Note: I tested this code at API level 10 and it worked fine.

5 comments:

  1. Can you please give a link to down load a source code because i am getting error it is looking for the SQLite DB
    or can you please send me mail on darjidhruvit@gmail.com

    ReplyDelete
  2. can u plz pass me the code . my email id id trupti.its.me@gmail.com

    ReplyDelete
  3. does your code work for android 4.0 as well? I am getting a null pointer exception on cursor. Please let me know

    ReplyDelete
    Replies
    1. Now google has provided the official api for calendar, so refer this link:

      http://developer.android.com/guide/topics/providers/calendar-provider.html

      Delete
  4. this is not working in jelly bean OS. Fine for other below versions.

    ReplyDelete