Question

I would like to display the list of installed calendars in android in the settings screen and select one among them. I saw this functionality in an android application Cal. Screenshot of the list of installed calendars in Cal app can be found here.

What I would like to know is "Is it possible to display the list of calendars using <preference> under res/XML"?

or

Do I have to select the list of calendars using PackageManager to find the list of all installed applications and displaying only the calendar applications?

I tried using <preference> using the below method

<Preference android:title="@string/pref_select_calendar" >
    <intent
        android:action="android.intent.action.PICK"
        android:data="content://calendar/calendars" />
</Preference>

But I've got android.content.ActivityNotFoundException: No Activity found to handle Intent

{ act=android.intent.action.PICK dat=content://calendar/calenders }

What am I missing? or the approach I'm trying is not correct? Any pointers will be very helpful. Thank you.

Was it helpful?

Solution

You'll have to query the CalendarProvider (available since API level 14)'s Calendars table for available calendars. The following snippet will show you how:

final String[] EVENT_PROJECTION = new String[]{
        CalendarContract.Calendars._ID,
        CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
        CalendarContract.Calendars.CALENDAR_COLOR
    };

    final ContentResolver cr = getContentResolver();
    final Uri uri = CalendarContract.Calendars.CONTENT_URI;
    Cursor cur = cr.query(uri, EVENT_PROJECTION, null, null, null);
    final List<CalendarInfo> result = Lists.newArrayList();

    while (cur.moveToNext()) {
        /* do something with the cursor:
           Long id = cur.getLong(0);
           String name = cur.getString(1);
           int color = cur.getInt(2);
        */
    }

Since you're doing IO work (providers are basically SQLite databases), it's a solid idea to wrap everything into a separate (non-UI) thread; I'd go with RxJava.

If you don't like playing with cursors, queries and boilerplate code, use the CalendarWrapper library. It takes care of mapping objects and database rows to and from, CRUD operations can be performed with object methods. For example in your case a single line would do the magic:

final List<Calendar> calendars = Calendar.getCalendarsForQuery(null, null, null, getContentResolver());

After you get a hold of the available calendars, just put them in a list and show it in a dialog, that's the easiest way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top