SweSnow
SweSnow

Reputation: 17364

Android read calendar events

I'm trying to create a interface to choose calenar events but I have run into some issues. On my devices I get the correct events but many of my users have reported the functionality isn't working and some shows events that aren't even in the calendar. On a 4.1 Samsung device I tested on the app crashed so what I'm wondering is; what is the correct way to display a list of all calendar events? Here's the code I'm using right now:

 Cursor cursor = getActivity().getContentResolver().query(Uri.parse
("content://com.android.calendar/events"),
 new String[]{"calendar_id", "title", "description",
"dtstart", "dtend", "eventLocation"}, "calendar_id=1", null, null);

        cursor.moveToFirst();

        int length = cursor.getCount();

        for (int i = 0; i < length; i++) {

                CalendarEvent ce = new CalendarEvent();

                ce.setTitle(cursor.getString(1));
                ce.setNote(cursor.getString(2));
                ce.setDate(cursor.getLong(3));

                if (cursor.getString(1).length() > 0) {
                    mItems.add(ce);
                }

                cursor.moveToNext();
        }

        cursor.close();

Upvotes: 1

Views: 1321

Answers (1)

matiash
matiash

Reputation: 55350

I would suspect that the culprit is this condition: "calendar_id=1".

A device can have multiple calendars. It's not guaranteed that the one with id=1 is the primary one (and even if you used the primary one, the user may have events in multiple different calendars -- e.g. personal and work).

So, it depends on what you want to do exactly. You should either:

  • use the primary calendar (the one with IS_PRIMARY, but see caveat above), or
  • have the user select a single calendar for using your app (querying the Calendars table) and then using that calendar_id from then on, or
  • if you want events from all calendars, remove the calendar_id filter.

Upvotes: 2

Related Questions