Example usage for android.content ContentValues size

List of usage examples for android.content ContentValues size

Introduction

In this page you can find the example usage for android.content ContentValues size.

Prototype

public int size() 

Source Link

Document

Returns the number of values.

Usage

From source file:at.bitfire.davdroid.resource.LocalCalendar.java

@Override
public void updateMetaData(WebDavResource.Properties properties) throws LocalStorageException {
    ContentValues values = new ContentValues();

    final String displayName = properties.getDisplayName();
    if (displayName != null)
        values.put(Calendars.CALENDAR_DISPLAY_NAME, displayName);

    final Integer color = properties.getColor();
    if (color != null)
        values.put(Calendars.CALENDAR_COLOR, color);

    try {/*  ww w .  ja va  2s .  c  om*/
        if (values.size() > 0)
            providerClient.update(ContentUris.withAppendedId(calendarsURI(), id), values, null, null);
    } catch (RemoteException e) {
        throw new LocalStorageException(e);
    }
}

From source file:im.r_c.android.dbox.SQLBuilder.java

static ContentValues buildContentValues(TableInfo tableInfo, Object obj) {
    ContentValues values = new ContentValues();
    for (ColumnInfo ci : tableInfo.mColumnMap.values()) {
        if (TableInfo.COLUMN_ID.equals(ci.mName)) {
            continue;
        }/*from  www .  j a va2s .c o m*/

        try {
            switch (ci.mType) {
            case ColumnInfo.TYPE_BOOLEAN:
                values.put(ci.mName, ci.mField.getBoolean(obj) ? 1 : 0);
                break;
            case ColumnInfo.TYPE_BYTE:
                values.put(ci.mName, ci.mField.getByte(obj));
                break;
            case ColumnInfo.TYPE_SHORT:
                values.put(ci.mName, ci.mField.getShort(obj));
                break;
            case ColumnInfo.TYPE_INT:
                values.put(ci.mName, ci.mField.getInt(obj));
                break;
            case ColumnInfo.TYPE_LONG:
                values.put(ci.mName, ci.mField.getLong(obj));
                break;
            case ColumnInfo.TYPE_FLOAT:
                values.put(ci.mName, ci.mField.getFloat(obj));
                break;
            case ColumnInfo.TYPE_DOUBLE:
                values.put(ci.mName, ci.mField.getDouble(obj));
                break;
            case ColumnInfo.TYPE_STRING:
                values.put(ci.mName, (String) ci.mField.get(obj));
                break;
            case ColumnInfo.TYPE_DATE:
                Date date = (Date) ci.mField.get(obj);
                values.put(ci.mName, date.getTime());
                break;
            case ColumnInfo.TYPE_BYTE_ARRAY:
                values.put(ci.mName, (byte[]) ci.mField.get(obj));
                break;
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    if (values.size() != tableInfo.mColumnMap.size() - 1) {
        // "values" contains all column values of the table except "id",
        // so normally this block will NEVER be executed.
        throw new UnknownError();
    }

    return values;
}

From source file:edu.cens.loci.provider.LociDbUtils.java

private int updateData(ContentValues values, Cursor c, boolean callerIsSyncAdapter) {
    if (values.size() == 0)
        return 0;

    final SQLiteDatabase db = mDbHelper.getWritableDatabase();

    final String mimeType = c.getString(DataUpdateQuery.MIMETYPE);
    DataRowHandler rowHandler = getDataRowHandler(mimeType);
    if (rowHandler.update(db, values, c, callerIsSyncAdapter)) {
        return 1;
    } else {//from ww  w  .  ja va2  s .c o m
        return 0;
    }
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Insert the given rowId with the values in the cvValues. If certain metadata
 * values are not specified in the cvValues, then suitable default values may
 * be supplied for them./*from   w ww. ja va 2 s  .c  o m*/
 * 
 * If a row with this rowId and certain matching metadata fields is present,
 * then an exception is thrown.
 * 
 * @param db
 * @param tableId
 * @param orderedColumns
 * @param cvValues
 * @param uuid
 */
public void insertDataIntoExistingDBTableWithId(SQLiteDatabase db, String tableId,
        ArrayList<ColumnDefinition> orderedColumns, ContentValues cvValues, String uuid) {

    if (cvValues.size() <= 0) {
        throw new IllegalArgumentException(t + ": No values to add into table " + tableId);
    }

    ContentValues cvDataTableVal = new ContentValues();
    cvDataTableVal.put(DataTableColumns.ID, uuid);
    cvDataTableVal.putAll(cvValues);

    upsertDataIntoExistingDBTable(db, tableId, orderedColumns, cvDataTableVal, false);
}

From source file:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

/**
 * Update the given rowId with the values in the cvValues. If certain metadata
 * values are not specified in the cvValues, then suitable default values may
 * be supplied for them. Furthermore, if the cvValues do not specify certain
 * metadata fields, then an exception may be thrown if there are more than one
 * row matching this rowId./*from   w  ww.  j  av  a  2 s  . c om*/
 * 
 * @param db
 * @param tableId
 * @param orderedColumns
 * @param cvValues
 * @param rowId
 */
public void updateDataInExistingDBTableWithId(SQLiteDatabase db, String tableId,
        ArrayList<ColumnDefinition> orderedColumns, ContentValues cvValues, String rowId) {

    if (cvValues.size() <= 0) {
        throw new IllegalArgumentException(t + ": No values to add into table " + tableId);
    }

    ContentValues cvDataTableVal = new ContentValues();
    cvDataTableVal.put(DataTableColumns.ID, rowId);
    cvDataTableVal.putAll(cvValues);

    upsertDataIntoExistingDBTable(db, tableId, orderedColumns, cvDataTableVal, true);
}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * Convenience method for updating rows in the database.
 *
 * @param table the table to update in/*from  w ww  .  ja v a2  s.  c o m*/
 * @param values a map from column names to new column values. null is a
 *            valid value that will be translated to NULL.
 * @param whereClause the optional WHERE clause to apply when updating.
 *            Passing null will update all rows.
 * @param whereArgs You may include ?s in the where clause, which
 *            will be replaced by the values from whereArgs. The values
 *            will be bound as Strings.
 * @param conflictAlgorithm for update conflict resolver
 * @return the number of rows affected
 */
public int updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs,
        @ConflictAlgorithm int conflictAlgorithm) {
    if (values == null || values.size() == 0) {
        throw new IllegalArgumentException("Empty values");
    }

    acquireReference();
    try {
        StringBuilder sql = new StringBuilder(120);
        sql.append("UPDATE ");
        sql.append(CONFLICT_VALUES[conflictAlgorithm]);
        sql.append(table);
        sql.append(" SET ");

        // move all bind args to one array
        int setValuesSize = values.size();
        int bindArgsSize = (whereArgs == null) ? setValuesSize : (setValuesSize + whereArgs.length);
        Object[] bindArgs = new Object[bindArgsSize];
        int i = 0;
        for (Map.Entry<String, Object> entry : values.valueSet()) {
            sql.append((i > 0) ? "," : "");
            sql.append(entry.getKey());
            bindArgs[i++] = entry.getValue();
            sql.append("=?");
        }
        if (whereArgs != null) {
            for (i = setValuesSize; i < bindArgsSize; i++) {
                bindArgs[i] = whereArgs[i - setValuesSize];
            }
        }
        if (!TextUtils.isEmpty(whereClause)) {
            sql.append(" WHERE ");
            sql.append(whereClause);
        }

        SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
        try {
            return statement.executeUpdateDelete();
        } finally {
            statement.close();
        }
    } finally {
        releaseReference();
    }
}

From source file:com.rks.musicx.misc.utils.Helper.java

/**
 * Edit Song Tags/*from   w ww  . j  av  a2s.c om*/
 *
 * @param context
 * @param song
 * @return
 */
public static boolean editSongTags(Context context, Song song) {
    File f = new File(song.getmSongPath());
    if (f.exists()) {
        try {
            AudioFile audioFile = AudioFileIO.read(f);
            if (audioFile == null) {
                return false;
            }
            TagOptionSingleton.getInstance().setAndroid(true);
            Tag tag = audioFile.getTag();
            if (tag == null) {
                return false;
            }
            String year = song.getYear();
            String title = song.getTitle();
            String album = song.getAlbum();
            String artist = song.getArtist();
            String lyrics = song.getLyrics();
            tag.deleteField(FieldKey.LYRICS);
            tag.setField(FieldKey.LYRICS, Html.fromHtml(lyrics).toString());
            ContentValues values = new ContentValues();
            if (title != null) {
                tag.setField(FieldKey.TITLE, title);
                values.put(MediaStore.Audio.Media.TITLE, title);
            }
            if (artist != null) {
                tag.setField(FieldKey.ARTIST, artist);
                values.put(MediaStore.Audio.Media.ARTIST, artist);
            }
            if (album != null) {
                tag.setField(FieldKey.ALBUM, album);
                Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                        new String[] { BaseColumns._ID, MediaStore.Audio.AlbumColumns.ALBUM,
                                MediaStore.Audio.AlbumColumns.ALBUM_KEY, MediaStore.Audio.AlbumColumns.ARTIST },
                        MediaStore.Audio.AlbumColumns.ALBUM + " = ?", new String[] { album },
                        MediaStore.Audio.Albums.DEFAULT_SORT_ORDER);

                if (cursor != null && cursor.moveToFirst()) {
                    long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
                    values.put(MediaStore.Audio.Media.ALBUM_ID, id);
                    cursor.close();
                } else {
                    values.put(MediaStore.Audio.Media.ALBUM, album);
                }
            }
            if (song.getTrackNumber() != -1) {
                tag.setField(FieldKey.TRACK, String.valueOf(song.getTrackNumber()));
                values.put(MediaStore.Audio.Media.TRACK, song.getTrackNumber());
            }
            if (year != null && year.length() > 0) {
                tag.setField(FieldKey.YEAR, "" + year);
                values.put(MediaStore.Audio.Media.YEAR, year);
            }
            if (values.size() > 0) {
                context.getContentResolver().update(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, values,
                        android.provider.MediaStore.Audio.Media._ID + "=?",
                        new String[] { String.valueOf(song.getId()) });
            } else {
                return false;
            }
            audioFile.setTag(tag);
            AudioFileIO.write(audioFile);
        } catch (CannotReadException | CannotWriteException | InvalidAudioFrameException | TagException
                | IOException | ReadOnlyFileException e) {
            e.printStackTrace();
        }
        return true;
    } else {
        return false;
    }
}

From source file:io.requery.android.database.sqlite.SQLiteDatabase.java

/**
 * General method for inserting a row into the database.
 *
 * @param table the table to insert the row into
 * @param nullColumnHack optional; may be <code>null</code>.
 *            SQL doesn't allow inserting a completely empty row without
 *            naming at least one column name.  If your provided <code>initialValues</code> is
 *            empty, no column names are known and an empty row can't be inserted.
 *            If not set to null, the <code>nullColumnHack</code> parameter
 *            provides the name of nullable column name to explicitly insert a NULL into
 *            in the case where your <code>initialValues</code> is empty.
 * @param initialValues this map contains the initial column values for the
 *            row. The keys should be the column names and the values the
 *            column values//from   w ww  . j av a2s . co m
 * @param conflictAlgorithm for insert conflict resolver
 * @return the row ID of the newly inserted row
 * OR the primary key of the existing row if the input param 'conflictAlgorithm' =
 * {@link #CONFLICT_IGNORE}
 * OR -1 if any error
 */
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public long insertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues,
        @ConflictAlgorithm int conflictAlgorithm) {
    acquireReference();
    try {
        StringBuilder sql = new StringBuilder();
        sql.append("INSERT");
        sql.append(CONFLICT_VALUES[conflictAlgorithm]);
        sql.append(" INTO ");
        sql.append(table);
        sql.append('(');

        Object[] bindArgs = null;
        int size = (initialValues != null && initialValues.size() > 0) ? initialValues.size() : 0;
        if (size > 0) {
            bindArgs = new Object[size];
            int i = 0;
            for (Map.Entry<String, Object> entry : initialValues.valueSet()) {
                sql.append((i > 0) ? "," : "");
                sql.append(entry.getKey());
                bindArgs[i++] = entry.getValue();
            }
            sql.append(')');
            sql.append(" VALUES (");
            for (i = 0; i < size; i++) {
                sql.append((i > 0) ? ",?" : "?");
            }
        } else {
            sql.append(nullColumnHack + ") VALUES (NULL");
        }
        sql.append(')');

        SQLiteStatement statement = new SQLiteStatement(this, sql.toString(), bindArgs);
        try {
            return statement.executeInsert();
        } finally {
            statement.close();
        }
    } finally {
        releaseReference();
    }
}

From source file:com.android.calendar.alerts.AlertService.java

/**
 * Processes the query results and bucketizes the alerts.
 *
 * @param highPriorityEvents This will contain future events, and concurrent events
 *     that started recently (less than the interval DEPRIORITIZE_GRACE_PERIOD_MS).
 * @param mediumPriorityEvents This will contain concurrent events that started
 *     more than DEPRIORITIZE_GRACE_PERIOD_MS ago.
 * @param lowPriorityEvents Will contain events that have ended.
 * @return Returns the number of new alerts to fire.  If this is 0, it implies
 *     a quiet update./*from ww  w .  j  a  v  a2 s  .c  o m*/
 */
static int processQuery(final Cursor alertCursor, final Context context, final long currentTime,
        ArrayList<NotificationInfo> highPriorityEvents, ArrayList<NotificationInfo> mediumPriorityEvents,
        ArrayList<NotificationInfo> lowPriorityEvents) {
    // Experimental reminder setting to only remind for events that have
    // been responded to with "yes" or "maybe".
    String skipRemindersPref = Utils.getSharedPreference(context,
            OtherPreferences.KEY_OTHER_REMINDERS_RESPONDED, "");
    // Skip no-response events if the "Skip Reminders" preference has the second option,
    // "If declined or not responded", is selected.
    // Note that by default, the first option will be selected, so this will be false.
    boolean remindRespondedOnly = skipRemindersPref
            .equals(context.getResources().getStringArray(R.array.preferences_skip_reminders_values)[1]);
    // Experimental reminder setting to silence reminders when they are
    // during the pre-defined quiet hours.
    boolean useQuietHours = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS, false);
    // Note that the start time may be either before or after the end time,
    // depending on whether quiet hours cross through midnight.
    int quietHoursStartHour = OtherPreferences.QUIET_HOURS_DEFAULT_START_HOUR;
    int quietHoursStartMinute = OtherPreferences.QUIET_HOURS_DEFAULT_START_MINUTE;
    int quietHoursEndHour = OtherPreferences.QUIET_HOURS_DEFAULT_END_HOUR;
    int quietHoursEndMinute = OtherPreferences.QUIET_HOURS_DEFAULT_END_MINUTE;
    if (useQuietHours) {
        quietHoursStartHour = Utils.getSharedPreference(context,
                OtherPreferences.KEY_OTHER_QUIET_HOURS_START_HOUR,
                OtherPreferences.QUIET_HOURS_DEFAULT_START_HOUR);
        quietHoursStartMinute = Utils.getSharedPreference(context,
                OtherPreferences.KEY_OTHER_QUIET_HOURS_START_MINUTE,
                OtherPreferences.QUIET_HOURS_DEFAULT_START_MINUTE);
        quietHoursEndHour = Utils.getSharedPreference(context, OtherPreferences.KEY_OTHER_QUIET_HOURS_END_HOUR,
                OtherPreferences.QUIET_HOURS_DEFAULT_END_HOUR);
        quietHoursEndMinute = Utils.getSharedPreference(context,
                OtherPreferences.KEY_OTHER_QUIET_HOURS_END_MINUTE,
                OtherPreferences.QUIET_HOURS_DEFAULT_END_MINUTE);
    }
    Time time = new Time();

    ContentResolver cr = context.getContentResolver();
    HashMap<Long, NotificationInfo> eventIds = new HashMap<Long, NotificationInfo>();
    int numFired = 0;
    try {
        while (alertCursor.moveToNext()) {
            final long alertId = alertCursor.getLong(ALERT_INDEX_ID);
            final long eventId = alertCursor.getLong(ALERT_INDEX_EVENT_ID);
            final int minutes = alertCursor.getInt(ALERT_INDEX_MINUTES);
            final String eventName = alertCursor.getString(ALERT_INDEX_TITLE);
            final String description = alertCursor.getString(ALERT_INDEX_DESCRIPTION);
            final String location = alertCursor.getString(ALERT_INDEX_EVENT_LOCATION);
            final int status = alertCursor.getInt(ALERT_INDEX_SELF_ATTENDEE_STATUS);
            final boolean declined = status == Attendees.ATTENDEE_STATUS_DECLINED;
            final boolean responded = status != Attendees.ATTENDEE_STATUS_NONE
                    && status != Attendees.ATTENDEE_STATUS_INVITED;
            final long beginTime = alertCursor.getLong(ALERT_INDEX_BEGIN);
            final long endTime = alertCursor.getLong(ALERT_INDEX_END);
            final Uri alertUri = ContentUris.withAppendedId(CalendarAlerts.CONTENT_URI, alertId);
            final long alarmTime = alertCursor.getLong(ALERT_INDEX_ALARM_TIME);
            boolean forceQuiet = false;
            if (useQuietHours) {
                // Quiet hours have been set.
                time.set(alarmTime);
                // Check whether the alarm will fire after the quiet hours
                // start time and/or before the quiet hours end time.
                boolean alarmAfterQuietHoursStart = (time.hour > quietHoursStartHour
                        || (time.hour == quietHoursStartHour && time.minute >= quietHoursStartMinute));
                boolean alarmBeforeQuietHoursEnd = (time.hour < quietHoursEndHour
                        || (time.hour == quietHoursEndHour && time.minute <= quietHoursEndMinute));
                // Check if quiet hours crosses through midnight, iff:
                // start hour is after end hour, or
                // start hour is equal to end hour, and start minute is
                // after end minute.
                // i.e. 22:30 - 06:45; 12:45 - 12:00
                //      01:05 - 10:30; 05:00 - 05:30
                boolean quietHoursCrossesMidnight = quietHoursStartHour > quietHoursEndHour
                        || (quietHoursStartHour == quietHoursEndHour
                                && quietHoursStartMinute > quietHoursEndMinute);
                if (quietHoursCrossesMidnight) {
                    // Quiet hours crosses midnight. Alarm should be quiet
                    // if it's after start time OR before end time.
                    if (alarmAfterQuietHoursStart || alarmBeforeQuietHoursEnd) {
                        forceQuiet = true;
                    }
                } else {
                    // Quiet hours doesn't cross midnight. Alarm should be
                    // quiet if it's after start time AND before end time.
                    if (alarmAfterQuietHoursStart && alarmBeforeQuietHoursEnd) {
                        forceQuiet = true;
                    }
                }
            }
            int state = alertCursor.getInt(ALERT_INDEX_STATE);
            final boolean allDay = alertCursor.getInt(ALERT_INDEX_ALL_DAY) != 0;

            // Use app local storage to keep track of fired alerts to fix problem of multiple
            // installed calendar apps potentially causing missed alarms.
            boolean newAlertOverride = false;
            if (AlertUtils.BYPASS_DB && ((currentTime - alarmTime) / MINUTE_MS < 1)) {
                // To avoid re-firing alerts, only fire if alarmTime is very recent.  Otherwise
                // we can get refires for non-dismissed alerts after app installation, or if the
                // SharedPrefs was cleared too early.  This means alerts that were timed while
                // the phone was off may show up silently in the notification bar.
                boolean alreadyFired = AlertUtils.hasAlertFiredInSharedPrefs(context, eventId, beginTime,
                        alarmTime);
                if (!alreadyFired) {
                    newAlertOverride = true;
                }
            }

            if (DEBUG) {
                StringBuilder msgBuilder = new StringBuilder();
                msgBuilder.append("alertCursor result: alarmTime:").append(alarmTime).append(" alertId:")
                        .append(alertId).append(" eventId:").append(eventId).append(" state: ").append(state)
                        .append(" minutes:").append(minutes).append(" declined:").append(declined)
                        .append(" responded:").append(responded).append(" beginTime:").append(beginTime)
                        .append(" endTime:").append(endTime).append(" allDay:").append(allDay)
                        .append(" alarmTime:").append(alarmTime).append(" forceQuiet:").append(forceQuiet);
                if (AlertUtils.BYPASS_DB) {
                    msgBuilder.append(" newAlertOverride: " + newAlertOverride);
                }
                Log.d(TAG, msgBuilder.toString());
            }

            ContentValues values = new ContentValues();
            int newState = -1;
            boolean newAlert = false;

            // Uncomment for the behavior of clearing out alerts after the
            // events ended. b/1880369
            //
            // if (endTime < currentTime) {
            //     newState = CalendarAlerts.DISMISSED;
            // } else

            // Remove declined events
            boolean sendAlert = !declined;
            // Check for experimental reminder settings.
            if (remindRespondedOnly) {
                // If the experimental setting is turned on, then only send
                // the alert if you've responded to the event.
                sendAlert = sendAlert && responded;
            }
            if (sendAlert) {
                if (state == CalendarAlerts.STATE_SCHEDULED || newAlertOverride) {
                    newState = CalendarAlerts.STATE_FIRED;
                    numFired++;
                    // If quiet hours are forcing the alarm to be silent,
                    // keep newAlert as false so it will not make noise.
                    if (!forceQuiet) {
                        newAlert = true;
                    }

                    // Record the received time in the CalendarAlerts table.
                    // This is useful for finding bugs that cause alarms to be
                    // missed or delayed.
                    values.put(CalendarAlerts.RECEIVED_TIME, currentTime);
                }
            } else {
                newState = CalendarAlerts.STATE_DISMISSED;
            }

            // Update row if state changed
            if (newState != -1) {
                values.put(CalendarAlerts.STATE, newState);
                state = newState;

                if (AlertUtils.BYPASS_DB) {
                    AlertUtils.setAlertFiredInSharedPrefs(context, eventId, beginTime, alarmTime);
                }
            }

            if (state == CalendarAlerts.STATE_FIRED) {
                // Record the time posting to notification manager.
                // This is used for debugging missed alarms.
                values.put(CalendarAlerts.NOTIFY_TIME, currentTime);
            }

            // Write row to if anything changed
            if (values.size() > 0)
                cr.update(alertUri, values, null, null);

            if (state != CalendarAlerts.STATE_FIRED) {
                continue;
            }

            // TODO: Prefer accepted events in case of ties.
            NotificationInfo newInfo = new NotificationInfo(eventName, location, description, beginTime,
                    endTime, eventId, allDay, newAlert);

            // Adjust for all day events to ensure the right bucket.  Don't use the 1/4 event
            // duration grace period for these.
            long beginTimeAdjustedForAllDay = beginTime;
            String tz = null;
            if (allDay) {
                tz = TimeZone.getDefault().getID();
                beginTimeAdjustedForAllDay = Utils.convertAlldayUtcToLocal(null, beginTime, tz);
            }

            // Handle multiple alerts for the same event ID.
            if (eventIds.containsKey(eventId)) {
                NotificationInfo oldInfo = eventIds.get(eventId);
                long oldBeginTimeAdjustedForAllDay = oldInfo.startMillis;
                if (allDay) {
                    oldBeginTimeAdjustedForAllDay = Utils.convertAlldayUtcToLocal(null, oldInfo.startMillis,
                            tz);
                }

                // Determine whether to replace the previous reminder with this one.
                // Query results are sorted so this one will always have a lower start time.
                long oldStartInterval = oldBeginTimeAdjustedForAllDay - currentTime;
                long newStartInterval = beginTimeAdjustedForAllDay - currentTime;
                boolean dropOld;
                if (newStartInterval < 0 && oldStartInterval > 0) {
                    // Use this reminder if this event started recently
                    dropOld = Math.abs(newStartInterval) < MIN_DEPRIORITIZE_GRACE_PERIOD_MS;
                } else {
                    // ... or if this one has a closer start time.
                    dropOld = Math.abs(newStartInterval) < Math.abs(oldStartInterval);
                }

                if (dropOld) {
                    // This is a recurring event that has a more relevant start time,
                    // drop other reminder in favor of this one.
                    //
                    // It will only be present in 1 of these buckets; just remove from
                    // multiple buckets since this occurrence is rare enough that the
                    // inefficiency of multiple removals shouldn't be a big deal to
                    // justify a more complicated data structure.  Expired events don't
                    // have individual notifications so we don't need to clean that up.
                    highPriorityEvents.remove(oldInfo);
                    mediumPriorityEvents.remove(oldInfo);
                    if (DEBUG) {
                        Log.d(TAG, "Dropping alert for recurring event ID:" + oldInfo.eventId + ", startTime:"
                                + oldInfo.startMillis + " in favor of startTime:" + newInfo.startMillis);
                    }
                } else {
                    // Skip duplicate reminders for the same event instance.
                    continue;
                }
            }

            // TODO: Prioritize by "primary" calendar
            eventIds.put(eventId, newInfo);
            long highPriorityCutoff = currentTime - getGracePeriodMs(beginTime, endTime, allDay);

            if (beginTimeAdjustedForAllDay > highPriorityCutoff) {
                // High priority = future events or events that just started
                highPriorityEvents.add(newInfo);
            } else if (allDay && tz != null && DateUtils.isToday(beginTimeAdjustedForAllDay)) {
                // Medium priority = in progress all day events
                mediumPriorityEvents.add(newInfo);
            } else {
                lowPriorityEvents.add(newInfo);
            }
        }
        // TODO(cwren) add beginTime/startTime
        GlobalDismissManager.processEventIds(context, eventIds.keySet());
    } finally {
        if (alertCursor != null) {
            alertCursor.close();
        }
    }
    return numFired;
}

From source file:com.android.mail.browse.ConversationCursor.java

/**
 * Returns a Conversation object for the current position, or null if it has not yet been
 * cached./*from  w ww.  j  a v a2 s  . co m*/
 *
 * This method will apply any cached column data to the result.
 *
 */
public Conversation getCachedConversation() {
    Conversation result = mUnderlyingCursor.getConversation();
    if (result == null) {
        return null;
    }

    // apply any cached values
    // but skip over any cached values that aren't part of the cursor projection
    final ContentValues values = mCacheMap.get(mUnderlyingCursor.getInnerUri());
    if (values != null) {
        final ContentValues queryableValues = new ContentValues();
        for (String key : values.keySet()) {
            if (!mColumnNameSet.contains(key)) {
                continue;
            }
            putInValues(queryableValues, key, values.get(key));
        }
        if (queryableValues.size() > 0) {
            // copy-on-write to help ensure the underlying cached Conversation is immutable
            // of course, any callers this method should also try not to modify them
            // overmuch...
            result = new Conversation(result);
            result.applyCachedValues(queryableValues);
        }
    }
    return result;
}