generate Calendar Selection - Android Android OS

Android examples for Android OS:Calendar Contract

Description

generate Calendar Selection

Demo Code


import android.content.Context;
import android.database.Cursor;
import android.provider.CalendarContract;
import android.util.Log;
import android.util.Pair;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;

public class Main{
    private static final String SQL_TAUTOLOGY = "1=1";
    public static String generateCalendarSelection(Context context) {
        Set<String> calendars = getSelectedCalendars(context);
        int count = calendars.size();

        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < count; i++) {
            if (i != 0) {
                sb.append(" OR ");
            }//  w w  w  . j  a  v  a 2 s .co  m

            sb.append(CalendarContract.Events.CALENDAR_ID);
            sb.append(" = ?");
        }

        if (sb.length() == 0) {
            sb.append(SQL_TAUTOLOGY); // constant expression to prevent returning null
        }

        return sb.toString();
    }
    public static Set<String> getSelectedCalendars(Context context) {

        Set<String> selectedCalendars = null;
        final List<Pair<String, Boolean>> allCalendars = getAllCalendars(context);

        // Build a set of all visible calendars in case we don't have a selection set in
        // the preferences.
        selectedCalendars = new HashSet<String>();
        for (Pair<String, Boolean> pair : allCalendars) {
            if (pair.second) {
                selectedCalendars.add(pair.first);
            }
        }

        return selectedCalendars;
    }
    public static List<Pair<String, Boolean>> getAllCalendars(
            Context context) {
        // Only return calendars that are marked as synced to device.
        // (This is different from the display flag)
        List<Pair<String, Boolean>> calendars = new ArrayList<Pair<String, Boolean>>();

        try {
            Cursor cursor = context.getContentResolver().query(
                    CalendarContract.Calendars.CONTENT_URI,
                    CalendarsQuery.PROJECTION,
                    CalendarContract.Calendars.SYNC_EVENTS + "=1", null,
                    null);

            if (cursor != null) {
                while (cursor.moveToNext()) {
                    calendars.add(new Pair<String, Boolean>(cursor
                            .getString(CalendarsQuery.ID), cursor
                            .getInt(CalendarsQuery.VISIBLE) == 1));

                }

                cursor.close();
            }

        } catch (SecurityException e) {
            Log.v("launcher_calendar", e.getMessage());
            return null;
        }

        return calendars;
    }
}

Related Tutorials