/** * Commodity method for the building of the ContentValues object starting from the EventInfo representation. * The method will return a ContentValues that will be utilised for the insert of an event * * @param context application's context * @return ContentValues representation of the CalendarInfo object */ private ContentValues toInsertContentValues(Context context) { final ContentValues contentValues = toContentValues(); if (contentValues.containsKey(Events._ID) || contentValues.containsKey(Events.CALENDAR_DISPLAY_NAME)) { Log.w(EventInfo.class.getSimpleName(), "TThe EventInfo to insert shouldn't have id and calendarDisplayName defined, they are automatically removed"); contentValues.remove(Events._ID); id = null; contentValues.remove(Events.CALENDAR_DISPLAY_NAME); calendarDisplayName = null; } if (isRecurrentEvent()) { contentValues.remove(Events.DTEND); if (endDate != null) { contentValues.put(Events.DURATION, "P" + ((endDate.getTime() - startDate.getTime()) / 1000) + "S"); } } if (!contentValues.containsKey(Events.EVENT_TIMEZONE)) { String timezone = CalendarInfo.getCompleteInformation(context, calendarId).getAsString(Calendars.CALENDAR_TIME_ZONE); if (timezone == null) { timezone = TimeZone.getDefault().getDisplayName(); } contentValues.put(Events.EVENT_TIMEZONE, timezone); } return contentValues; }
public static void addCalendars(Context context, List<CalendarInfo> outCalendars) { final String primary = "\"primary\""; final String[] projection = { Calendars._ID, Calendars.CALENDAR_DISPLAY_NAME, "(" + Calendars.ACCOUNT_NAME + "=" + Calendars.OWNER_ACCOUNT + ") AS " + primary }; final String selection = primary + " = 1"; Cursor cursor = null; try { cursor = context.getContentResolver().query(Calendars.CONTENT_URI, projection, selection, null, null); if (cursor == null) { return; } while (cursor.moveToNext()) { final CalendarInfo ci = new CalendarInfo(); ci.name = cursor.getString(1); ci.userId = context.getUserId(); outCalendars.add(ci); } } finally { if (cursor != null) { cursor.close(); } } }
public static void insertEvent(Context context, long startTime, long endTime, String title) { ContentResolver resolver = context.getContentResolver(); if (queryHandler == null) queryHandler = new QueryHandler(resolver); ContentValues values = new ContentValues(); values.put(Events.DTSTART, startTime); values.put(Events.DTEND, endTime); values.put(Events.TITLE, title); if (BuildConfig.DEBUG) Log.d(TAG, "Calendar query start"); queryHandler.startQuery(CALENDAR, values, Calendars.CONTENT_URI, CALENDAR_PROJECTION, null, null, null); }
private long getCalendarId() { String[] projection = new String[]{Calendars._ID}; //String selection = Calendars.ACCOUNT_NAME + "=Biermacht AND" + Calendars.ACCOUNT_TYPE + "=" + CalendarContract.ACCOUNT_TYPE_LOCAL; String selection = "(" + Calendars.ACCOUNT_NAME + " = ?) AND (" + Calendars.ACCOUNT_TYPE + " = ?)"; String[] selectionArgs = new String[]{"Biermacht", CalendarContract.ACCOUNT_TYPE_LOCAL}; // use the same values as above: //String[] selArgs = new String[]{"Biermacht", CalendarContract.ACCOUNT_TYPE_LOCAL}; Cursor cursor = c.getContentResolver().query(Calendars.CONTENT_URI, projection, selection, selectionArgs, null); if (cursor.moveToFirst()) { return cursor.getLong(0); } return - 1; }
/** * Commodity method for the building of the ContentValues object starting from the CalendarInfo representation * * @return ContentValues representation of the CalendarInfo object */ public ContentValues toContentValues() { ContentValues contentValues = new ContentValues(); contentValues.put(Calendars._ID, id); if (accountName != null) { contentValues.put(Calendars.ACCOUNT_NAME, accountName); } contentValues.put(Calendars.NAME, name == null ? accountName : name); contentValues.put(Calendars.CALENDAR_DISPLAY_NAME, displayName == null ? name : displayName); if (ownerAccount != null) { contentValues.put(Calendars.OWNER_ACCOUNT, ownerAccount); } if (color != null) { contentValues.put(Calendars.CALENDAR_COLOR, color); } if (visible != null) { contentValues.put(Calendars.VISIBLE, visible ? 1 : 0); } if (accountType != null) { contentValues.put(Calendars.ACCOUNT_TYPE, accountType); } return contentValues; }
/** * Deletes all Events from the EventsDB and the Calendar from the CalendarDB * identified by the _ID and ACCOUNT_TYPE * * @param mContext * @param account * @return true if delete was successful */ public boolean deleteCalendar(Account account, long calendarId) { deleteAllEvents(account, calendarId); ContentResolver cr = mContext.getContentResolver(); String selection = "((" + Calendars._ID + " = ?) AND (" + Calendars.ACCOUNT_TYPE + " = ?))"; String[] selectionArgs = new String[] { Long.toString(calendarId), Constants.ACCOUNT_TYPE }; long ret = cr.delete(Calendars.CONTENT_URI, selection, selectionArgs); if (ret == 1) { return true; } else if (ret == 0) { return false; } else { Log.w(TAG, "WARNING deleteCalendar() deleted " + ret + " rows, should be only one!"); return true; } }
/** * Returns a list of calendars available on the phone * @param context * @return list of CalendarInstances */ public static ArrayList<CalendarInstance> getCalendars(Context context) { ArrayList<CalendarInstance> result = new ArrayList<CalendarInstance>(); Cursor cur = null; ContentResolver cr = context.getContentResolver(); Uri uri = Calendars.CONTENT_URI; String selection = null; String[] selectionArgs = null; cur = cr.query(uri, new String[]{Calendars._ID, Calendars.NAME, Calendars.CALENDAR_DISPLAY_NAME, Calendars.ACCOUNT_NAME}, selection, selectionArgs, null); while (cur.moveToNext()) { result.add(new CalendarInstance(cur.getLong(cur.getColumnIndex(Calendars._ID)), cur.getString(cur.getColumnIndex(Calendars.CALENDAR_DISPLAY_NAME)), cur.getString(cur.getColumnIndex(Calendars.ACCOUNT_NAME)))); } cur.close(); return result; }
public void populateCalendars() { String[] projection = new String[]{Calendars._ID, Calendars.NAME, Calendars.ACCOUNT_NAME, Calendars.ACCOUNT_TYPE}; Cursor calCursor = this .getActivity() .getContentResolver() .query(Calendars.CONTENT_URI, projection, null, null, Calendars._ID + " DESC"); calendarNames = new ArrayList<String>(); calendarAccounts = new ArrayList<String>(); calendarTypes = new ArrayList<String>(); calendarIds = new ArrayList<Long>(); if (calCursor.moveToFirst()) { do { String name = calCursor.getString(1); if (name == null) { name = "Sin nombre"; } calendarNames.add(name); calendarAccounts.add(calCursor.getString(2)); calendarTypes.add(calCursor.getString(3)); calendarIds.add(calCursor.getLong(0)); } while (calCursor.moveToNext()); } }
public void populateCalendars() { String[] projection = new String[]{Calendars._ID, Calendars.NAME, Calendars.ACCOUNT_NAME, Calendars.ACCOUNT_TYPE}; Cursor calCursor = this.getActivity().getContentResolver() .query(Calendars.CONTENT_URI, projection, null, null, Calendars._ID + " DESC"); calendarNames = new ArrayList<String>(); calendarAccounts = new ArrayList<String>(); calendarTypes = new ArrayList<String>(); calendarIds = new ArrayList<Long>(); if (calCursor.moveToFirst()) { do { String name = calCursor.getString(1); if (name == null) { name = "Sin nombre"; } calendarNames.add(name); calendarAccounts.add(calCursor.getString(2)); calendarTypes.add(calCursor.getString(3)); calendarIds.add(calCursor.getLong(0)); } while (calCursor.moveToNext()); } }
/** * Deletes all Events from the EventsDB and the Calendar from the CalendarDB * identified by the _ID and ACCOUNT_TYPE * * @param mContext * @param account * @return true if delete was successful */ public boolean deleteCalendar(Account account, long calendarId) { deleteAllEvents(account, calendarId); Uri url = asSyncAdapter(Calendars.CONTENT_URI, account.name, account.type); ContentResolver cr = mContext.getContentResolver(); String selection = "((" + Calendars._ID + " = ?) AND (" + Calendars.ACCOUNT_TYPE + " = ?))"; String[] selectionArgs = new String[] { Long.toString(calendarId), Constants.ACCOUNT_TYPE }; long ret = cr.delete(Calendars.CONTENT_URI, selection, selectionArgs); if (ret == 1) { return true; } else if (ret == 0) { return false; } else { Log.w(TAG, "WARNING deleteCalendar() deleted " + ret + " rows, should be only one!"); return true; } }
public void doSaveAction() { // Cancel the previous operation mCalendarsUpdater.cancelOperation(mUpdateToken); mUpdateToken++; // This is to allow us to do queries and updates with the same AsyncQueryHandler without // accidently canceling queries. if(mUpdateToken < MIN_UPDATE_TOKEN) { mUpdateToken = MIN_UPDATE_TOKEN; } Iterator<Long> changeKeys = mCalendarChanges.keySet().iterator(); while (changeKeys.hasNext()) { long id = changeKeys.next(); boolean newSynced = mCalendarChanges.get(id); Uri uri = ContentUris.withAppendedId(Calendars.CONTENT_URI, id); ContentValues values = new ContentValues(); values.put(Calendars.VISIBLE, newSynced ? 1 : 0); values.put(Calendars.SYNC_EVENTS, newSynced ? 1 : 0); mCalendarsUpdater.startUpdate(mUpdateToken, id, uri, values, null, null); } }
/** * Performs a query to return all visible instances in the given range * that match the given selection. This is a blocking function and * should not be done on the UI thread. This will cause an expansion of * recurring events to fill this time range if they are not already * expanded and will slow down for larger time ranges with many * recurring events. * * @param cr The ContentResolver to use for the query * @param projection The columns to return * @param begin The start of the time range to query in UTC millis since * epoch * @param end The end of the time range to query in UTC millis since * epoch * @param selection Filter on the query as an SQL WHERE statement * @param selectionArgs Args to replace any '?'s in the selection * @param orderBy How to order the rows as an SQL ORDER BY statement * @return A Cursor of instances matching the selection */ private static final Cursor instancesQuery(ContentResolver cr, String[] projection, int startDay, int endDay, String selection, String[] selectionArgs, String orderBy) { String WHERE_CALENDARS_SELECTED = Calendars.VISIBLE + "=?"; String[] WHERE_CALENDARS_ARGS = {"1"}; String DEFAULT_SORT_ORDER = "begin ASC"; Uri.Builder builder = Instances.CONTENT_BY_DAY_URI.buildUpon(); ContentUris.appendId(builder, startDay); ContentUris.appendId(builder, endDay); if (TextUtils.isEmpty(selection)) { selection = WHERE_CALENDARS_SELECTED; selectionArgs = WHERE_CALENDARS_ARGS; } else { selection = "(" + selection + ") AND " + WHERE_CALENDARS_SELECTED; if (selectionArgs != null && selectionArgs.length > 0) { selectionArgs = Arrays.copyOf(selectionArgs, selectionArgs.length + 1); selectionArgs[selectionArgs.length - 1] = WHERE_CALENDARS_ARGS[0]; } else { selectionArgs = WHERE_CALENDARS_ARGS; } } return cr.query(builder.build(), projection, selection, selectionArgs, orderBy == null ? DEFAULT_SORT_ORDER : orderBy); }
@Override public void bindView(View view, Context context, Cursor cursor) { View colorBar = view.findViewById(R.id.color); int colorColumn = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_COLOR); int nameColumn = cursor.getColumnIndexOrThrow(Calendars.CALENDAR_DISPLAY_NAME); int ownerColumn = cursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT); if (colorBar != null) { colorBar.setBackgroundColor(Utils.getDisplayColorFromColor(cursor .getInt(colorColumn))); } TextView name = (TextView) view.findViewById(R.id.calendar_name); if (name != null) { String displayName = cursor.getString(nameColumn); name.setText(displayName); TextView accountName = (TextView) view.findViewById(R.id.account_name); if (accountName != null) { accountName.setText(cursor.getString(ownerColumn)); accountName.setVisibility(TextView.VISIBLE); } } }
private int findDefaultCalendarPosition(Cursor calendarsCursor) { if (calendarsCursor.getCount() <= 0) { return -1; } String defaultCalendar = Utils.getSharedPreference( mActivity, GeneralPreferences.KEY_DEFAULT_CALENDAR, (String) null); if (defaultCalendar == null) { return 0; } int calendarsOwnerColumn = calendarsCursor.getColumnIndexOrThrow(Calendars.OWNER_ACCOUNT); int position = 0; calendarsCursor.moveToPosition(-1); while (calendarsCursor.moveToNext()) { if (defaultCalendar.equals(calendarsCursor.getString(calendarsOwnerColumn))) { return position; } position++; } return 0; }
private void saveReminders() { ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(3); boolean changed = EditEventHelper.saveReminders(ops, mModel.mId, mModel.mReminders, mOriginalModel.mReminders, false /* no force save */); if (!changed) { return; } AsyncQueryService service = new AsyncQueryService(getActivity()); service.startBatch(0, null, Calendars.CONTENT_URI.getAuthority(), ops, 0); // Update the "hasAlarm" field for the event Uri uri = ContentUris.withAppendedId(Events.CONTENT_URI, mModel.mId); int len = mModel.mReminders.size(); boolean hasAlarm = len > 0; if (hasAlarm != mOriginalModel.mHasAlarm) { ContentValues values = new ContentValues(); values.put(Events.HAS_ALARM, hasAlarm ? 1 : 0); service.startUpdate(0, null, uri, values, null, null, 0); } Toast.makeText(mContext, R.string.saving_event, Toast.LENGTH_SHORT).show(); }
@Override protected EnumMap<KeyIndex, String> initContentProviderKeys() { EnumMap<KeyIndex, String> keys = new EnumMap<KeyIndex, String>( KeyIndex.class); keys.put(KeyIndex.CALENDARS_ID, Calendars._ID); keys.put(KeyIndex.CALENDARS_NAME, Calendars.NAME); keys.put(KeyIndex.CALENDARS_DISPLAY_NAME, Calendars.CALENDAR_DISPLAY_NAME); keys.put(KeyIndex.CALENDARS_VISIBLE, Calendars.VISIBLE); keys.put(KeyIndex.EVENTS_ID, Events._ID); keys.put(KeyIndex.EVENTS_CALENDAR_ID, Events.CALENDAR_ID); keys.put(KeyIndex.EVENTS_DESCRIPTION, Events.DESCRIPTION); keys.put(KeyIndex.EVENTS_LOCATION, Events.EVENT_LOCATION); keys.put(KeyIndex.EVENTS_SUMMARY, Events.TITLE); keys.put(KeyIndex.EVENTS_START, Events.DTSTART); keys.put(KeyIndex.EVENTS_END, Events.DTEND); keys.put(KeyIndex.EVENTS_RRULE, Events.RRULE); keys.put(KeyIndex.EVENTS_ALL_DAY, Events.ALL_DAY); keys.put(KeyIndex.INSTANCES_ID, Instances._ID); keys.put(KeyIndex.INSTANCES_EVENT_ID, Instances.EVENT_ID); keys.put(KeyIndex.INSTANCES_BEGIN, Instances.BEGIN); keys.put(KeyIndex.INSTANCES_END, Instances.END); keys.put(KeyIndex.ATTENDEES_ID, Attendees._ID); keys.put(KeyIndex.ATTENDEES_EVENT_ID, Attendees.EVENT_ID); keys.put(KeyIndex.ATTENDEES_NAME, Attendees.ATTENDEE_NAME); keys.put(KeyIndex.ATTENDEES_EMAIL, Attendees.ATTENDEE_EMAIL); keys.put(KeyIndex.ATTENDEES_STATUS, Attendees.ATTENDEE_STATUS); return keys; }
@Override protected Cursor queryCalendars(String[] projection, String selection, String[] selectionArgs, String sortOrder) { return this.cordova.getActivity().getContentResolver().query( Calendars.CONTENT_URI, projection, selection, selectionArgs, sortOrder); }
@Override protected EnumMap<KeyIndex, String> initContentProviderKeys() { EnumMap<KeyIndex, String> keys = new EnumMap<KeyIndex, String>( KeyIndex.class); keys.put(KeyIndex.CALENDARS_ID, Calendars._ID); keys.put(KeyIndex.CALENDARS_NAME, Calendars.NAME); keys.put(KeyIndex.CALENDARS_VISIBLE, Calendars.VISIBLE); keys.put(KeyIndex.EVENTS_ID, Events._ID); keys.put(KeyIndex.EVENTS_CALENDAR_ID, Events.CALENDAR_ID); keys.put(KeyIndex.EVENTS_DESCRIPTION, Events.DESCRIPTION); keys.put(KeyIndex.EVENTS_LOCATION, Events.EVENT_LOCATION); keys.put(KeyIndex.EVENTS_SUMMARY, Events.TITLE); keys.put(KeyIndex.EVENTS_START, Events.DTSTART); keys.put(KeyIndex.EVENTS_END, Events.DTEND); keys.put(KeyIndex.EVENTS_RRULE, Events.RRULE); keys.put(KeyIndex.EVENTS_ALL_DAY, Events.ALL_DAY); keys.put(KeyIndex.INSTANCES_ID, Instances._ID); keys.put(KeyIndex.INSTANCES_EVENT_ID, Instances.EVENT_ID); keys.put(KeyIndex.INSTANCES_BEGIN, Instances.BEGIN); keys.put(KeyIndex.INSTANCES_END, Instances.END); keys.put(KeyIndex.ATTENDEES_ID, Attendees._ID); keys.put(KeyIndex.ATTENDEES_EVENT_ID, Attendees.EVENT_ID); keys.put(KeyIndex.ATTENDEES_NAME, Attendees.ATTENDEE_NAME); keys.put(KeyIndex.ATTENDEES_EMAIL, Attendees.ATTENDEE_EMAIL); keys.put(KeyIndex.ATTENDEES_STATUS, Attendees.ATTENDEE_STATUS); return keys; }
/** * List the user's calendars * * @return All calendars of the user */ public Calendar[] listCalendars() { ContentResolver cr = context.getContentResolver(); Uri calendarUri = Calendars.CONTENT_URI; Cursor cur = cr.query(calendarUri, CALENDAR_PROJECTION, null, null, null); if (cur == null) return null; Calendar[] res = new Calendar[cur.getCount()]; int i = 0; while (cur.moveToNext()) { long calendarId = cur.getLong(CALENDAR_PROJECTION_ID_INDEX); res[i] = new Calendar(calendarId, cur.getString(CALENDAR_PROJECTION_DISPLAY_NAME_INDEX), cur.getInt(CALENDAR_PROJECTION_IS_SYNCED_INDEX) == 1); i++; } cur.close(); return res; }
@SuppressLint("MissingPermission") private void setSummaryCMSDP() { String prefVolumeDataSummary = _context.getString(R.string.calendars_multiselect_summary_text_not_selected); if (Permissions.checkCalendar(_context)) { if (!value.isEmpty()) { String[] splits = value.split("\\|"); if (splits.length == 1) { boolean found = false; Cursor cur; ContentResolver cr = _context.getContentResolver(); Uri uri = Calendars.CONTENT_URI; String selection = Calendars._ID + "=" + splits[0]; //noinspection MissingPermission cur = cr.query(uri, CALENDAR_PROJECTION, selection, null, null); if (cur != null) { //while (cur.moveToNext()) { if (cur.moveToFirst()) { found = true; prefVolumeDataSummary = cur.getString(PROJECTION_DISPLAY_NAME_INDEX); //break; } cur.close(); } if (!found) prefVolumeDataSummary = _context.getString(R.string.calendars_multiselect_summary_text_selected) + ": " + splits.length; } else prefVolumeDataSummary = _context.getString(R.string.calendars_multiselect_summary_text_selected) + ": " + splits.length; } } setSummary(prefVolumeDataSummary); }
private JSONArray allEvents(String accountType, String accountName, boolean dirtiesOnly) { JSONArray calendars = calendarAccessor.getCalendars( accountType, accountName); String[] calendarIds = new String[calendars.length()]; for (int i = 0; i < calendars.length(); i++) { try { calendarIds[i] = String.valueOf( calendars.getJSONObject(i).getLong(Calendars._ID)); } catch (JSONException e) { Log.w(LOG_TAG, e); return null; } } String query = "( " + Events.CALENDAR_ID + " in ( " // no android way to use 'in' operator with parameters. + TextUtils.join(",", calendarIds) +" ))" ; if (dirtiesOnly) { query += " AND ( " + Events.DIRTY + " = 1 )" ; } Cursor c = context.getContentResolver().query( Events.CONTENT_URI, EVENT_COLUMNS, query, null, null ); JSONArray events = eventsRows2JSONArray(c); c.close(); return events; }
/** Fetch all event of the specified account, by calendars */ public JSONArray all(String accountType, String accountName) { JSONArray calendars = calendarAccessor.getCalendars( accountType, accountName); for (int i = 0; i < calendars.length(); i++) { try { JSONObject calendar = calendars.getJSONObject(i); calendar.put("events", getEvents(calendar.getInt(Calendars._ID))); } catch (JSONException e) { Log.w(LOG_TAG, e); } } return calendars; }
/** Fetch all calendars of the specified account */ public JSONArray getCalendars(String accountType, String accountName) { Cursor c = context.getContentResolver().query( Calendars.CONTENT_URI, CALENDAR_COLUMNS, "( " + Calendars.ACCOUNT_NAME + " = ? ) AND ( " + Calendars.ACCOUNT_TYPE + " = ? )", new String[] { accountName, accountType }, null ); Log.d(LOG_TAG, "GetCalendars, after cursor."); // Convert to JSON. return Tools.rows2JSONArray(c, CALENDAR_COLUMNS); }
public String addCalendar(JSONObject calendar, String accountType, String accountName) { Uri uri = context.getContentResolver().insert( Tools.asSyncAdapter(Calendars.CONTENT_URI, accountType, accountName), Tools.json2Row(calendar, CALENDAR_COLUMNS) ); return uri.getLastPathSegment(); }
public void updateCalendar(JSONObject calendar, String accountType, String accountName) { try { context.getContentResolver().update( Tools.asSyncAdapter(Calendars.CONTENT_URI, accountType, accountName), Tools.json2Row(calendar, CALENDAR_COLUMNS), Calendars._ID + " = ? ", new String[] { String.valueOf(calendar.get(Calendars._ID)) } ); } catch (JSONException e) { Log.w(LOG_TAG, e); } }
public int deleteCalendar(JSONObject calendar, String accountType, String accountName) { try { ContentResolver cr = context.getContentResolver(); return cr.delete( Tools.asSyncAdapter(Calendars.CONTENT_URI, accountType, accountName), Calendars._ID + " = ? ", new String[] {String.valueOf(calendar.getLong(Calendars._ID))} ); } catch (JSONException e) { Log.w(LOG_TAG, e); return -1; } }
/** * Create a new event starting from the information set into the {@code eventInfo}. * If the event is correctly added to the Android Calendar Provider then the {@code eventInfo} * will be updated with the assigned identifier and displayed name of the event. * * @param context application's context * @param eventInfo EventInfo representation of the event to create * @return true if the event is successfully insert into the Android Calendar Provider */ public static boolean insert(Context context, EventInfo eventInfo) { if (eventInfo.isRecurrentEvent()) { //TODO: manage insertion of recurrent event return false; } final ContentValues contentValues = eventInfo.toInsertContentValues(context); if (hasMandatoryInsertField(contentValues)) { final Uri uri = context.getContentResolver().insert(UriBuilder.EVENTS_URI, contentValues); eventInfo.id = Long.valueOf(uri.getLastPathSegment()); eventInfo.calendarDisplayName = getInformation(context, eventInfo.id, new String[]{Calendars.CALENDAR_DISPLAY_NAME}).getAsString(Calendars.CALENDAR_DISPLAY_NAME); return true; } return false; }
/** * Extract a CalendarInfo object from its representation as ContentValues (value extracted querying the Android Content Provider) * * @param contentValues information extracted from the content provider * @return the CalendarInfo representation of the {@code contentValues} * @throws IllegalArgumentException if the {@code contentValues} cannot be parsed to a CalendarInfo object */ public static CalendarInfo fromContentValues(ContentValues contentValues) { CalendarInfo calendarInfo = new CalendarInfo(); try { calendarInfo.id = contentValues.getAsLong(Calendars._ID); calendarInfo.accountName = contentValues.getAsString(Calendars.ACCOUNT_NAME); calendarInfo.name = contentValues.getAsString(Calendars.NAME); if (calendarInfo.name == null) { calendarInfo.name = calendarInfo.accountName; } calendarInfo.displayName = contentValues.getAsString(Calendars.CALENDAR_DISPLAY_NAME); if (calendarInfo.displayName == null) { calendarInfo.displayName = calendarInfo.name; } calendarInfo.ownerAccount = contentValues.getAsString(Calendars.OWNER_ACCOUNT); calendarInfo.color = contentValues.getAsInteger(Calendars.CALENDAR_COLOR); calendarInfo.visible = contentValues.getAsInteger(Calendars.VISIBLE) == 1; calendarInfo.accountType = contentValues.getAsString(Calendars.ACCOUNT_TYPE); return calendarInfo; } catch (NullPointerException e) { StringBuilder errorString = new StringBuilder(); StringBuilder missingColumns = new StringBuilder(); errorString.append("There is NOT all the required parameters in the contentValues\nThe required keys are: "); for (String col : COLUMNS) { errorString.append(col).append(", "); if (!contentValues.containsKey(col)) { missingColumns.append(col).append(", "); } } errorString.setLength(errorString.length() - 2); if (missingColumns.length() > 0) { missingColumns.setLength(missingColumns.length() - 2); } errorString.append("\n the following columns are missing: ").append(missingColumns); throw new IllegalArgumentException(errorString.toString()); } }
/** * Commodity method to generate the correct filter string and arguments list according to the owners and visibility defined * * @param owners filter on the owners, null to not apply the filter * @param visible filter on the visibility, null to not apply the filter * @return a {@code Pair} containing as first field the selection string and as second field the selection arguments */ private static Pair<String, String[]> filterOnOwnersAndVisible(Collection<String> owners, Boolean visible) { String selection = null; String selectionArgs[] = null; if (owners != null && owners.size() == 0) { owners = null; } if (owners != null || visible != null) { // selection will look like // visible=? AND (accountName=? OR accountName=? OR accountName=? OR accountName=?) StringBuilder builder = new StringBuilder(); List<String> arguments = new ArrayList<>(); if (visible != null) { builder.append(Calendars.VISIBLE).append("=?"); arguments.add(visible ? "1" : "0"); } if (owners != null) { if (visible != null) { builder.append(" AND ("); } for (String owner : owners) { builder.append(Calendars.ACCOUNT_NAME).append("=? OR "); arguments.add(owner); } builder.setLength(builder.length() - 4); //4 is the length of " OR " if (visible != null) { builder.append(")"); } } selection = builder.toString(); selectionArgs = arguments.toArray(new String[arguments.size()]); } return Pair.create(selection, selectionArgs); }
/** * Commodity method for the building of the ContentValues object starting from the CalendarInfo representation. * The method will return a ContentValues that will be utilised for a new local calendar * * @return ContentValues representation of the CalendarInfo object */ private ContentValues toCreateLocalContentValues() { final ContentValues contentValues = toContentValues(); if (contentValues.containsKey(Calendars._ID)) { Log.w(getClass().getSimpleName(), "The CalendarInfo to insert shouldn't have id defined, they are automatically removed"); contentValues.remove(Calendars._ID); id = null; } contentValues.put(Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL); contentValues.put(Calendars.CALENDAR_ACCESS_LEVEL, Calendars.CAL_ACCESS_OWNER); return contentValues; }
/** * Commodity method for the building of the ContentValues object starting from the CalendarInfo representation. * The method will return a ContentValues that will be utilised for the update of the calendar * * @return ContentValues representation of the CalendarInfo object */ public ContentValues toUpdateContentValues() { final ContentValues contentValues = toContentValues(); if (contentValues.containsKey(Calendars.ACCOUNT_NAME)) { contentValues.remove(Calendars.ACCOUNT_NAME); contentValues.remove(Calendars.ACCOUNT_TYPE); contentValues.remove(Calendars.OWNER_ACCOUNT); } return contentValues; }
/** * Commodity method to check if the {@code contentValues} has all the required fields to complete successfully the creation * * @param contentValues ContentValues to insert * @return true if the {@code contentValues} has all the needed fields */ private static boolean hasMandatoryCreateField(ContentValues contentValues) { return contentValues.containsKey(Calendars.ACCOUNT_NAME) && contentValues.containsKey(Calendars.ACCOUNT_TYPE) && contentValues.containsKey(Calendars.NAME) && contentValues.containsKey(Calendars.CALENDAR_DISPLAY_NAME) && contentValues.containsKey(Calendars.CALENDAR_ACCESS_LEVEL); }
/** * Create a local calendar starting from the information set into the {@code calendarInfo}. * If the calendar is correctly added to the Android Calendar Provider then the {@code calendarInfo} * will be updated with the assigned identifier. * * @param context application's context * @param calendarInfo CalendarInfo representation of the calendar to create * @return true if the calendar is successfully insert into the Android Calendar Provider */ public static boolean createLocal(Context context, CalendarInfo calendarInfo) { final ContentValues contentValues = calendarInfo.toCreateLocalContentValues(); if (hasMandatoryCreateField(contentValues)) { final Uri.Builder uriBuilder = UriBuilder.getUri().buildUpon(); uriBuilder.appendQueryParameter(Calendars.ACCOUNT_NAME, calendarInfo.accountName); uriBuilder.appendQueryParameter(Calendars.ACCOUNT_TYPE, CalendarContract.ACCOUNT_TYPE_LOCAL); uriBuilder.appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true"); final Uri uri = context.getContentResolver().insert(uriBuilder.build(), contentValues); calendarInfo.id = Long.valueOf(uri.getLastPathSegment()); return true; } return false; }
public static LocalCalendar[] findAll(Account account, ContentProviderClient providerClient, AccountSettings accountSettings) throws RemoteException { @Cleanup Cursor cursor = providerClient.query(calendarsURI(account), new String[] { Calendars._ID, Calendars.NAME, COLLECTION_COLUMN_CTAG, Calendars.CALENDAR_TIME_ZONE }, Calendars.DELETED + "=0 AND " + Calendars.SYNC_EVENTS + "=1", null, null); LinkedList<LocalCalendar> calendars = new LinkedList<LocalCalendar>(); while (cursor != null && cursor.moveToNext()) calendars.add(new LocalCalendar(account, providerClient, accountSettings, cursor.getInt(0), cursor.getString(3))); return calendars.toArray(new LocalCalendar[0]); }