Friday 5 August 2011

Retrieving Events from Calendar

ContentResolver cr = getContentResolver();
       
//Find out which calendars exist...

Cursor cursor_calendar;
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();

//Find out stored events in Calendar...

Cursor cursor_event;
if (Integer.parseInt(Build.VERSION.SDK) >= 8 ){
  cursor_event = cr.query(Uri.parse("content://com.android.calendar/events"), new String[]{ "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation" }, null, null, null);
else{
    cursor_event = cr.query(Uri.parse("content://calendar/events"), new String[]{ "calendar_id", "title", "description", "dtstart", "dtend", "eventLocation" }, null, null, null);
}
   
String add = null;
cursor_event.moveToFirst();
String[] CalNames = new String[cursor_event.getCount()];
int[] CalIds = new int[cursor_event.getCount()];
for (int i = 0; i < CalNames.length; i++) {
  CalIds[i] = cursor_event.getInt(0);
  CalNames[i] = "Event"+cursor_event.getInt(0)+": \nTitle: "+ cursor_event.getString(1)+"\nDescription: "+cursor_event.getString(2)+"\nStart Date: "+new Date(cursor_event.getLong(3))+"\nEnd Date : "+new Date(cursor_event.getLong(4))+"\nLocation : "+cursor_event.getString(5);
  if(add == null)
      add = CalNames[i];
  else{
      add += CalNames[i];
  }          
  cursor_event.moveToNext();
}
cursor_event.close();

Note: I tested this code on API level 10 and it is working fine.


1 comment:

  1. This is undocumented and unsupported. Google has repeatedly told you to not use undocumented content providers. This code will not work on all versions of Android. This content provider may not even exist on any given device. And Google may close down access to this content provider, as they have with others. Please use the Google Calendar GData API for manipulating a user's Google Calendar.

    ReplyDelete