Getting events from calendar

Akash Thakkar picture Akash Thakkar · May 4, 2011 · Viewed 72k times · Source

My issue is, I have to make one demo application in which I wants to read the events of the Google calendar, for that I have manually inserted the events like the title of event, the time of events and the details of the whole events. now I need to just read those events form that calendar. For that I have tried to use the gcode(google code) API which provides the calendar API class. But still I cant read those events.

Answer

Marco Massenzio picture Marco Massenzio · May 2, 2012

That code above is pretty awful (and it does not seem to work in ICS - definitely the column names are different)

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

provides a much better overview. A (much) simpler code to retrieve calendars:

public class CalendarContentResolver {
    public static final String[] FIELDS = { 
        CalendarContract.Calendars.NAME,
        CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
        CalendarContract.Calendars.CALENDAR_COLOR,
        CalendarContract.Calendars.VISIBLE 
    };

    public static final Uri CALENDAR_URI = Uri.parse("content://com.android.calendar/calendars");

    ContentResolver contentResolver;
    Set<String> calendars = new HashSet<String>();

    public  CalendarContentResolver(Context ctx) {
        contentResolver = ctx.getContentResolver();
    }

    public Set<String> getCalendars() {
        // Fetch a list of all calendars sync'd with the device and their display names
        Cursor cursor = contentResolver.query(CALENDAR_URI, FIELDS, null, null, null);

        try {
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    String name = cursor.getString(0);
                    String displayName = cursor.getString(1);
                    // This is actually a better pattern:
                    String color = cursor.getString(cursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_COLOR));
                    Boolean selected = !cursor.getString(3).equals("0");
                    calendars.add(displayName);  
                }
            }
        } catch (AssertionError ex) { /*TODO: log exception and bail*/ }

        return calendars;
    }
}

Hope this helps!