Example usage for android.content ContentValues containsKey

List of usage examples for android.content ContentValues containsKey

Introduction

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

Prototype

public boolean containsKey(String key) 

Source Link

Document

Returns true if this object has the named value.

Usage

From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java

/**
 * Send tagData changes to server//from w  w  w.  j  av a  2 s. c  om
 * @param setValues
 */
public void pushTagDataOnSave(TagData tagData, ContentValues values) {
    long remoteId;
    if (tagData.containsNonNullValue(TagData.REMOTE_ID))
        remoteId = tagData.getValue(TagData.REMOTE_ID);
    else {
        TagData forRemote = tagDataService.fetchById(tagData.getId(), TagData.REMOTE_ID);
        if (forRemote == null)
            return;
        remoteId = forRemote.getValue(TagData.REMOTE_ID);
    }
    boolean newlyCreated = remoteId == 0;

    ArrayList<Object> params = new ArrayList<Object>();

    if (values.containsKey(TagData.NAME.name)) {
        params.add("name");
        params.add(tagData.getValue(TagData.NAME));
    }

    if (values.containsKey(TagData.DELETION_DATE.name)) {
        params.add("deleted_at");
        params.add(tagData.getValue(TagData.DELETION_DATE));
    }

    if (values.containsKey(TagData.TAG_DESCRIPTION.name)) {
        params.add("description");
        params.add(tagData.getValue(TagData.TAG_DESCRIPTION));
    }

    if (values.containsKey(TagData.MEMBERS.name)) {
        params.add("members");
        try {
            JSONArray members = new JSONArray(tagData.getValue(TagData.MEMBERS));
            if (members.length() == 0)
                params.add("");
            else {
                ArrayList<Object> array = new ArrayList<Object>(members.length());
                for (int i = 0; i < members.length(); i++) {
                    JSONObject person = members.getJSONObject(i);
                    if (person.has("id"))
                        array.add(person.getLong("id"));
                    else {
                        if (person.has("name"))
                            array.add(person.getString("name") + " <" + person.getString("email") + ">");
                        else
                            array.add(person.getString("email"));
                    }
                }
                params.add(array);
            }

            addAbTestEventInfo(params);

        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    if (values.containsKey(TagData.FLAGS.name)) {
        params.add("is_silent");
        boolean silenced = tagData.getFlag(TagData.FLAGS, TagData.FLAG_SILENT);
        params.add(silenced ? "1" : "0");
    }

    if (params.size() == 0 || !checkForToken())
        return;

    if (!newlyCreated) {
        params.add("id");
        params.add(remoteId);
    }

    try {
        params.add("token");
        params.add(token);
        JSONObject result = actFmInvoker.invoke("tag_save", params.toArray(new Object[params.size()]));
        if (newlyCreated) {
            tagData.setValue(TagData.REMOTE_ID, result.optLong("id"));
            tagData.putTransitory(SyncFlags.ACTFM_SUPPRESS_SYNC, true);
            tagDataDao.saveExisting(tagData);
        }
    } catch (ActFmServiceException e) {
        handleException("tag-save", e);

        try {
            fetchTag(tagData);
        } catch (IOException e1) {
            handleException("refetch-error-tag", e);
        } catch (JSONException e1) {
            handleException("refetch-error-tag", e);
        }
    } catch (IOException e) {
        addFailedPush(new FailedPush(PUSH_TYPE_TAG, tagData.getId()));
        handleException("tag-save", e);
    }
}

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

protected void populateIMPP(Contact c, ContentValues row) {
    String handle = row.getAsString(Im.DATA);

    Impp impp = null;/*from  w  w w.j a v a 2s . c o m*/
    switch (row.getAsInteger(Im.PROTOCOL)) {
    case Im.PROTOCOL_AIM:
        impp = Impp.aim(handle);
        break;
    case Im.PROTOCOL_MSN:
        impp = Impp.msn(handle);
        break;
    case Im.PROTOCOL_YAHOO:
        impp = Impp.yahoo(handle);
        break;
    case Im.PROTOCOL_SKYPE:
        impp = Impp.skype(handle);
        break;
    case Im.PROTOCOL_QQ:
        impp = new Impp("qq", handle);
        break;
    case Im.PROTOCOL_GOOGLE_TALK:
        impp = new Impp("google-talk", handle);
        break;
    case Im.PROTOCOL_ICQ:
        impp = Impp.icq(handle);
        break;
    case Im.PROTOCOL_JABBER:
        impp = Impp.xmpp(handle);
        break;
    case Im.PROTOCOL_NETMEETING:
        impp = new Impp("netmeeting", handle);
        break;
    case Im.PROTOCOL_CUSTOM:
        impp = new Impp(row.getAsString(Im.CUSTOM_PROTOCOL), handle);
    }

    if (impp != null) {
        if (row.containsKey(Im.TYPE))
            switch (row.getAsInteger(Im.TYPE)) {
            case Im.TYPE_HOME:
                impp.addType(ImppType.HOME);
                break;
            case Im.TYPE_WORK:
                impp.addType(ImppType.WORK);
                break;
            case Im.TYPE_CUSTOM:
                String customType = row.getAsString(Im.LABEL);
                if (StringUtils.isNotEmpty(customType))
                    impp.addType(ImppType.get(labelToXName(customType)));
            }

        c.getImpps().add(impp);
    }
}

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

/**
 * Returns the conversation uris for the Conversations that the ConversationCursor is treating
 * as deleted.  This is an optimization to allow clients to determine if an item has been
 * removed, without having to iterate through the whole cursor
 *///from  w w  w .  j  a v  a2  s  .c om
public Set<String> getDeletedItems() {
    synchronized (mCacheMapLock) {
        // Walk through the cache and return the list of uris that have been deleted
        final Set<String> deletedItems = Sets.newHashSet();
        final Iterator<Map.Entry<String, ContentValues>> iter = mCacheMap.entrySet().iterator();
        final StringBuilder uriBuilder = new StringBuilder();
        while (iter.hasNext()) {
            final Map.Entry<String, ContentValues> entry = iter.next();
            final ContentValues values = entry.getValue();
            if (values.containsKey(DELETED_COLUMN)) {
                // Since clients of the conversation cursor see conversation ConversationCursor
                // provider uris, we need to make sure that this also returns these uris
                deletedItems.add(uriToCachingUriString(entry.getKey(), uriBuilder));
            }
        }
        return deletedItems;
    }
}

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

/**
 * Returns the position, in the ConversationCursor, of the Conversation with the specified id.
 * The returned position will take into account any items that have been deleted.
 *//*from   w  w  w.ja  v a2 s .c  o  m*/
public int getConversationPosition(long conversationId) {
    final int underlyingPosition = mUnderlyingCursor.getPosition(conversationId);
    if (underlyingPosition < 0) {
        // The conversation wasn't found in the underlying cursor, return the underlying result.
        return underlyingPosition;
    }

    // Walk through each of the deleted items.  If the deleted item is before the underlying
    // position, decrement the position
    synchronized (mCacheMapLock) {
        int updatedPosition = underlyingPosition;
        final Iterator<Map.Entry<String, ContentValues>> iter = mCacheMap.entrySet().iterator();
        while (iter.hasNext()) {
            final Map.Entry<String, ContentValues> entry = iter.next();
            final ContentValues values = entry.getValue();
            if (values.containsKey(DELETED_COLUMN)) {
                // Since clients of the conversation cursor see conversation ConversationCursor
                // provider uris, we need to make sure that this also returns these uris
                final String conversationUri = entry.getKey();
                final int deletedItemPosition = mUnderlyingCursor.getPosition(conversationUri);
                if (deletedItemPosition == underlyingPosition) {
                    // The requested items has been deleted.
                    return -1;
                }

                if (deletedItemPosition >= 0 && deletedItemPosition < underlyingPosition) {
                    // This item has been deleted, but is still in the underlying cursor, at
                    // a position before the requested item.  Decrement the position of the
                    // requested item.
                    updatedPosition--;
                }
            }
        }
        return updatedPosition;
    }
}

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

private void upsertDataIntoExistingDBTable(SQLiteDatabase db, String tableId,
        ArrayList<ColumnDefinition> orderedColumns, ContentValues cvValues, boolean shouldUpdate) {
    String rowId = null;/* w  ww .  java 2 s.  c  o m*/
    String whereClause = null;
    boolean specifiesConflictType = cvValues.containsKey(DataTableColumns.CONFLICT_TYPE);
    boolean nullConflictType = specifiesConflictType && (cvValues.get(DataTableColumns.CONFLICT_TYPE) == null);
    String[] whereArgs = new String[specifiesConflictType ? (1 + (nullConflictType ? 0 : 1)) : 1];
    boolean update = false;

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

    ContentValues cvDataTableVal = new ContentValues();
    cvDataTableVal.putAll(cvValues);

    if (cvDataTableVal.containsKey(DataTableColumns.ID)) {
        // The user specified a row id; we need to determine whether to
        // insert or update the record, or to reject the action because
        // there are either checkpoint records for this row id, or, if
        // a server conflict is associated with this row, that the
        // _conflict_type to update was not specified.
        //
        // i.e., the tuple (_id, _conflict_type) should be unique. If
        // we find that there are more than 0 or 1 records matching this
        // tuple, then we should reject the update request.
        //
        // TODO: perhaps we want to allow updates to the local conflict
        // row if there are no checkpoints on it? I.e., change the
        // tri-state conflict type to a pair of states (local / remote).
        // and all local changes are flagged local. Remote only exists
        // if the server is in conflict.

        rowId = cvDataTableVal.getAsString(DataTableColumns.ID);
        if (rowId == null) {
            throw new IllegalArgumentException(DataTableColumns.ID + ", if specified, cannot be null");
        }

        if (specifiesConflictType) {
            if (nullConflictType) {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE
                        + " IS NULL";
                whereArgs[0] = rowId;
            } else {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE + " = ?";
                whereArgs[0] = rowId;
                whereArgs[1] = cvValues.getAsString(DataTableColumns.CONFLICT_TYPE);
            }
        } else {
            whereClause = DataTableColumns.ID + " = ?";
            whereArgs[0] = rowId;
        }

        String sel = "SELECT * FROM " + tableId + " WHERE " + whereClause;
        String[] selArgs = whereArgs;
        Cursor cursor = rawQuery(db, sel, selArgs);

        // There must be only one row in the db for the update to work
        if (shouldUpdate) {
            if (cursor.getCount() == 1) {
                update = true;
            } else if (cursor.getCount() > 1) {
                throw new IllegalArgumentException(
                        t + ": row id " + rowId + " has more than 1 row in table " + tableId);
            }
        } else {
            if (cursor.getCount() > 0) {
                throw new IllegalArgumentException(
                        t + ": id " + rowId + " is already present in table " + tableId);
            }
        }

    } else {
        rowId = "uuid:" + UUID.randomUUID().toString();
    }

    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields

    if (!cvDataTableVal.containsKey(DataTableColumns.ID)) {
        cvDataTableVal.put(DataTableColumns.ID, rowId);
    }

    if (update) {
        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.changed.name());
        }

        if (cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                && (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                && (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    } else {

        if (!cvDataTableVal.containsKey(DataTableColumns.ROW_ETAG)
                || cvDataTableVal.get(DataTableColumns.ROW_ETAG) == null) {
            cvDataTableVal.put(DataTableColumns.ROW_ETAG, DataTableColumns.DEFAULT_ROW_ETAG);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.CONFLICT_TYPE)) {
            cvDataTableVal.putNull(DataTableColumns.CONFLICT_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_TYPE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_TYPE, DataTableColumns.DEFAULT_FILTER_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_VALUE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_VALUE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_VALUE, DataTableColumns.DEFAULT_FILTER_VALUE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FORM_ID)) {
            cvDataTableVal.putNull(DataTableColumns.FORM_ID);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                || (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    }

    cleanUpValuesMap(orderedColumns, cvDataTableVal);

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        if (update) {
            db.update(tableId, cvDataTableVal, whereClause, whereArgs);
        } else {
            db.insertOrThrow(tableId, null, cvDataTableVal);
        }

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }

}

From source file:org.tasks.gtasks.GoogleTaskSyncAdapter.java

/**
 * Synchronize with server when data changes
 */// w w  w. j ava  2 s.  co  m
private void pushTask(Task task, ContentValues values, GtasksInvoker invoker) throws IOException {
    for (Metadata deleted : getDeleted(task.getId())) {
        gtasksInvoker.deleteGtask(deleted.getValue(GtasksMetadata.LIST_ID),
                deleted.getValue(GtasksMetadata.ID));
        metadataDao.delete(deleted.getId());
    }

    Metadata gtasksMetadata = metadataDao.getFirstActiveByTaskAndKey(task.getId(), GtasksMetadata.METADATA_KEY);
    com.google.api.services.tasks.model.Task remoteModel;
    boolean newlyCreated = false;

    String remoteId;
    String listId = gtasksPreferenceService.getDefaultList();
    if (listId == null) {
        com.google.api.services.tasks.model.TaskList defaultList = invoker.getGtaskList(DEFAULT_LIST);
        if (defaultList != null) {
            listId = defaultList.getId();
            gtasksPreferenceService.setDefaultList(listId);
        } else {
            listId = DEFAULT_LIST;
        }
    }

    if (gtasksMetadata == null || !gtasksMetadata.containsNonNullValue(GtasksMetadata.ID)
            || TextUtils.isEmpty(gtasksMetadata.getValue(GtasksMetadata.ID))) { //Create case
        if (gtasksMetadata == null) {
            gtasksMetadata = gtasksMetadataFactory.createEmptyMetadata(task.getId());
        }
        if (gtasksMetadata.containsNonNullValue(GtasksMetadata.LIST_ID)) {
            listId = gtasksMetadata.getValue(GtasksMetadata.LIST_ID);
        }

        remoteModel = new com.google.api.services.tasks.model.Task();
        newlyCreated = true;
    } else { //update case
        remoteId = gtasksMetadata.getValue(GtasksMetadata.ID);
        listId = gtasksMetadata.getValue(GtasksMetadata.LIST_ID);
        remoteModel = new com.google.api.services.tasks.model.Task();
        remoteModel.setId(remoteId);
    }

    //If task was newly created but without a title, don't sync--we're in the middle of
    //creating a task which may end up being cancelled. Also don't sync new but already
    //deleted tasks
    if (newlyCreated && (!values.containsKey(Task.TITLE.name) || TextUtils.isEmpty(task.getTitle())
            || task.getDeletionDate() > 0)) {
        return;
    }

    //Update the remote model's changed properties
    if (values.containsKey(Task.DELETION_DATE.name) && task.isDeleted()) {
        remoteModel.setDeleted(true);
    }

    if (values.containsKey(Task.TITLE.name)) {
        remoteModel.setTitle(task.getTitle());
    }
    if (values.containsKey(Task.NOTES.name)) {
        remoteModel.setNotes(task.getNotes());
    }
    if (values.containsKey(Task.DUE_DATE.name) && task.hasDueDate()) {
        remoteModel.setDue(GtasksApiUtilities.unixTimeToGtasksDueDate(task.getDueDate()));
    }
    if (values.containsKey(Task.COMPLETION_DATE.name)) {
        if (task.isCompleted()) {
            remoteModel
                    .setCompleted(GtasksApiUtilities.unixTimeToGtasksCompletionTime(task.getCompletionDate()));
            remoteModel.setStatus("completed"); //$NON-NLS-1$
        } else {
            remoteModel.setCompleted(null);
            remoteModel.setStatus("needsAction"); //$NON-NLS-1$
        }
    }

    if (!newlyCreated) {
        try {
            invoker.updateGtask(listId, remoteModel);
        } catch (HttpNotFoundException e) {
            Timber.e(e, e.getMessage());
            metadataDao.delete(gtasksMetadata.getId());
            return;
        }
    } else {
        String parent = gtasksSyncService.getRemoteParentId(gtasksMetadata);
        String priorSibling = gtasksSyncService.getRemoteSiblingId(listId, gtasksMetadata);

        com.google.api.services.tasks.model.Task created = invoker.createGtask(listId, remoteModel, parent,
                priorSibling);

        if (created != null) {
            //Update the metadata for the newly created task
            gtasksMetadata.setValue(GtasksMetadata.ID, created.getId());
            gtasksMetadata.setValue(GtasksMetadata.LIST_ID, listId);
        } else {
            return;
        }
    }

    task.setModificationDate(DateUtilities.now());
    gtasksMetadata.setValue(GtasksMetadata.LAST_SYNC, DateUtilities.now() + 1000L);
    metadataDao.persist(gtasksMetadata);
    task.putTransitory(SyncFlags.GTASKS_SUPPRESS_SYNC, true);
    taskDao.saveExistingWithSqlConstraintCheck(task);
}

From source file:org.opendatakit.common.android.provider.impl.InstanceProviderImpl.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() != 3) {
        throw new SQLException("Unknown URI (does not specify instance!) " + uri);
    }/*  www .java  2  s.co  m*/

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);

    String tableId = segments.get(1);
    // _ID in UPLOADS_TABLE_NAME
    String instanceId = segments.get(2);

    SQLiteDatabase db = null;
    int count = 0;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);

        boolean success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

        String dbTableName = "\"" + tableId + "\"";

        // run the query to get all the ids...
        List<IdStruct> idStructs = new ArrayList<IdStruct>();
        Cursor ref = null;
        try {
            // use this provider's query interface to get the set of ids that
            // match (if any)
            ref = this.query(uri, null, where, whereArgs, null);
            if (ref.getCount() != 0) {
                ref.moveToFirst();
                do {
                    String iId = ODKDatabaseUtils.get().getIndexAsString(ref,
                            ref.getColumnIndex(InstanceColumns._ID));
                    String iIdDataTable = ODKDatabaseUtils.get().getIndexAsString(ref,
                            ref.getColumnIndex(InstanceColumns.DATA_INSTANCE_ID));
                    idStructs.add(new IdStruct(iId, iIdDataTable));
                } while (ref.moveToNext());
            }
        } finally {
            if (ref != null) {
                ref.close();
            }
        }

        // update the values string...
        if (values.containsKey(InstanceColumns.XML_PUBLISH_STATUS)) {
            Date xmlPublishDate = new Date();
            values.put(InstanceColumns.XML_PUBLISH_TIMESTAMP,
                    TableConstants.nanoSecondsFromMillis(xmlPublishDate.getTime()));
            String xmlPublishStatus = values.getAsString(InstanceColumns.XML_PUBLISH_STATUS);
            if (values.containsKey(InstanceColumns.DISPLAY_SUBTEXT) == false) {
                String text = getDisplaySubtext(xmlPublishStatus, xmlPublishDate);
                values.put(InstanceColumns.DISPLAY_SUBTEXT, text);
            }
        }

        db.beginTransaction();
        String[] args = new String[1];
        for (IdStruct idStruct : idStructs) {
            args[0] = idStruct.idUploadsTable;
            count += db.update(DatabaseConstants.UPLOADS_TABLE_NAME, values, InstanceColumns._ID + "=?", args);
        }
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

From source file:com.todoroo.astrid.actfm.sync.ActFmSyncService.java

/**
 * Synchronize with server when data changes
 *///from ww w.java2s  .c  om
public void pushTaskOnSave(Task task, ContentValues values) {
    Task taskForRemote = taskService.fetchById(task.getId(), Task.REMOTE_ID, Task.CREATION_DATE);

    long remoteId = 0;
    if (task.containsNonNullValue(Task.REMOTE_ID)) {
        remoteId = task.getValue(Task.REMOTE_ID);
    } else {
        if (taskForRemote == null)
            return;
        if (taskForRemote.containsNonNullValue(Task.REMOTE_ID))
            remoteId = taskForRemote.getValue(Task.REMOTE_ID);
    }

    long creationDate;
    if (task.containsValue(Task.CREATION_DATE)) {
        creationDate = task.getValue(Task.CREATION_DATE) / 1000L; // In seconds
    } else {
        if (taskForRemote == null)
            return;
        creationDate = taskForRemote.getValue(Task.CREATION_DATE) / 1000L; // In seconds
    }

    boolean newlyCreated = remoteId == 0;

    ArrayList<Object> params = new ArrayList<Object>();

    // prevent creation of certain types of tasks
    if (newlyCreated) {
        if (task.getValue(Task.TITLE).length() == 0)
            return;
        if (TaskApiDao.insignificantChange(values))
            return;
        values = task.getMergedValues();
    }

    if (values.containsKey(Task.TITLE.name)) {
        params.add("title");
        params.add(task.getValue(Task.TITLE));
    }
    if (values.containsKey(Task.DUE_DATE.name)) {
        params.add("due");
        params.add(task.getValue(Task.DUE_DATE) / 1000L);
        params.add("has_due_time");
        params.add(task.hasDueTime() ? 1 : 0);
    }
    if (values.containsKey(Task.NOTES.name)) {
        params.add("notes");
        params.add(task.getValue(Task.NOTES));
    }
    if (values.containsKey(Task.DELETION_DATE.name)) {
        params.add("deleted_at");
        params.add(task.getValue(Task.DELETION_DATE) / 1000L);
    }
    if (task.getTransitory(TaskService.TRANS_REPEAT_COMPLETE) != null) {
        params.add("completed");
        params.add(DateUtilities.now() / 1000L);
    } else if (values.containsKey(Task.COMPLETION_DATE.name)) {
        params.add("completed");
        params.add(task.getValue(Task.COMPLETION_DATE) / 1000L);
    }
    if (values.containsKey(Task.IMPORTANCE.name)) {
        params.add("importance");
        params.add(task.getValue(Task.IMPORTANCE));
    }
    if (values.containsKey(Task.RECURRENCE.name)
            || (values.containsKey(Task.FLAGS.name) && task.containsNonNullValue(Task.RECURRENCE))) {
        String recurrence = task.getValue(Task.RECURRENCE);
        if (!TextUtils.isEmpty(recurrence) && task.getFlag(Task.FLAGS, Task.FLAG_REPEAT_AFTER_COMPLETION))
            recurrence = recurrence + ";FROM=COMPLETION";
        params.add("repeat");
        params.add(recurrence);
    }

    boolean sharing = false;
    if (values.containsKey(Task.USER_ID.name) && task.getTransitory(TaskService.TRANS_ASSIGNED) != null) {
        if (task.getValue(Task.USER_ID) == Task.USER_ID_EMAIL) {
            try {
                JSONObject user = new JSONObject(task.getValue(Task.USER));
                String userEmail = user.optString("email");
                if (!TextUtils.isEmpty(userEmail)) {
                    params.add("user_email");
                    params.add(userEmail);

                    actFmDataService.addUserByEmail(userEmail);
                    sharing = true;
                }
            } catch (JSONException e) {
                Log.e("Error parsing user", task.getValue(Task.USER), e);
            }
        } else {
            params.add("user_id");
            if (task.getValue(Task.USER_ID) == Task.USER_ID_SELF)
                params.add(ActFmPreferenceService.userId());
            else
                params.add(task.getValue(Task.USER_ID));
        }
    }

    if (values.containsKey(Task.SHARED_WITH.name)) {
        try {
            JSONObject sharedWith = new JSONObject(task.getValue(Task.SHARED_WITH));
            if (sharedWith.has("p")) {
                JSONArray people = sharedWith.getJSONArray("p");
                for (int i = 0; i < people.length(); i++) {
                    params.add("share_with[]");
                    params.add(people.getString(i));
                }
                if (sharedWith.has("message")) {
                    String message = sharedWith.getString("message");
                    if (!TextUtils.isEmpty(message))
                        params.add("message");
                    params.add(message);
                }
            }
        } catch (JSONException e) {
            Log.e("Error parsing shared_with", task.getValue(Task.SHARED_WITH), e);
        }
        sharing = true;
    }

    if (sharing) {
        addAbTestEventInfo(params);
    }

    if (Flags.checkAndClear(Flags.TAGS_CHANGED) || newlyCreated) {
        TodorooCursor<Metadata> cursor = TagService.getInstance().getTags(task.getId(), false);
        try {
            if (cursor.getCount() == 0) {
                params.add("tags");
                params.add("");
            } else {
                Metadata metadata = new Metadata();
                for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
                    metadata.readFromCursor(cursor);
                    if (metadata.containsNonNullValue(TagService.REMOTE_ID)
                            && metadata.getValue(TagService.REMOTE_ID) > 0) {
                        params.add("tag_ids[]");
                        params.add(metadata.getValue(TagService.REMOTE_ID));
                    } else {
                        params.add("tags[]");
                        params.add(metadata.getValue(TagService.TAG));
                    }
                }
            }
        } finally {
            cursor.close();
        }
    }

    if (params.size() == 0 || !checkForToken())
        return;

    if (!newlyCreated) {
        params.add("id");
        params.add(remoteId);
    } else if (!values.containsKey(Task.TITLE.name)) {
        pushTask(task.getId());
        return;
    } else {
        params.add("created_at");
        params.add(creationDate);
    }

    try {
        params.add("token");
        params.add(token);
        JSONObject result = actFmInvoker.invoke("task_save", params.toArray(new Object[params.size()]));
        ArrayList<Metadata> metadata = new ArrayList<Metadata>();
        JsonHelper.taskFromJson(result, task, metadata);
    } catch (JSONException e) {
        handleException("task-save-json", e);
    } catch (IOException e) {
        if (notPermanentError(e)) {
            addFailedPush(new FailedPush(PUSH_TYPE_TASK, task.getId()));
        } else {
            handleException("task-save-io", e);
            task.setValue(Task.LAST_SYNC, DateUtilities.now() + 1000L);
        }
    }

    task.putTransitory(SyncFlags.ACTFM_SUPPRESS_SYNC, true);
    taskDao.saveExistingWithSqlConstraintCheck(task);
}

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

/**
 * Reset the cursor; this involves clearing out our cache map and resetting our various counts
 * The cursor should be reset whenever we get fresh data from the underlying cursor. The cache
 * is locked during the reset, which will block the UI, but for only a very short time
 * (estimated at a few ms, but we can profile this; remember that the cache will usually
 * be empty or have a few entries)/*  w  w w  . j  av a 2  s.  com*/
 */
private void resetCursor(UnderlyingCursorWrapper newCursorWrapper) {
    synchronized (mCacheMapLock) {
        // Walk through the cache
        final Iterator<Map.Entry<String, ContentValues>> iter = mCacheMap.entrySet().iterator();
        final long now = System.currentTimeMillis();
        while (iter.hasNext()) {
            Map.Entry<String, ContentValues> entry = iter.next();
            final ContentValues values = entry.getValue();
            final String key = entry.getKey();
            boolean withinTimeWindow = false;
            boolean removed = false;
            if (values != null) {
                Long updateTime = values.getAsLong(UPDATE_TIME_COLUMN);
                if (updateTime != null && ((now - updateTime) < REQUERY_ALLOWANCE_TIME)) {
                    LogUtils.d(LOG_TAG, "IN resetCursor, keep recent changes to %s", key);
                    withinTimeWindow = true;
                } else if (updateTime == null) {
                    LogUtils.e(LOG_TAG, "null updateTime from mCacheMap for key: %s", key);
                }
                if (values.containsKey(DELETED_COLUMN)) {
                    // Item is deleted locally AND deleted in the new cursor.
                    if (!newCursorWrapper.contains(key)) {
                        // Keep the deleted count up-to-date; remove the
                        // cache entry
                        mDeletedCount--;
                        removed = true;
                        LogUtils.d(LOG_TAG, "IN resetCursor, sDeletedCount decremented to: %d by %s",
                                mDeletedCount, key);
                    }
                }
            } else {
                LogUtils.e(LOG_TAG, "null ContentValues from mCacheMap for key: %s", key);
            }
            // Remove the entry if it was time for an update or the item was deleted by the user.
            if (!withinTimeWindow || removed) {
                iter.remove();
            }
        }

        // Swap cursor
        if (mUnderlyingCursor != null) {
            close();
        }
        mUnderlyingCursor = newCursorWrapper;

        mPosition = -1;
        mUnderlyingCursor.moveToPosition(mPosition);
        if (!mCursorObserverRegistered) {
            mUnderlyingCursor.registerContentObserver(mCursorObserver);
            mCursorObserverRegistered = true;

        }
        mRefreshRequired = false;

        // If the underlying cursor has received an update before we have gotten to this
        // point, we will want to make sure to refresh
        final boolean underlyingCursorUpdated = mUnderlyingCursor.isDataUpdated();
        mUnderlyingCursor.disableUpdateNotifications();
        if (underlyingCursorUpdated) {
            underlyingChanged();
        }
    }
    if (DEBUG)
        LogUtils.i(LOG_TAG, "OUT resetCursor, this=%s", this);
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

/**
 * Inserts an object into the database and flags it to be sent by
 * the transport layer./*  ww  w  .  j a v  a2s.c  om*/
 */
long addToFeed(String appId, String feedName, ContentValues values) {
    try {
        JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
        String type = values.getAsString(DbObject.TYPE);

        long nextSeqId = getFeedMaxSequenceId(Contact.MY_ID, feedName) + 1;
        long timestamp = new Date().getTime();
        json.put(DbObjects.TYPE, type);
        json.put(DbObjects.FEED_NAME, feedName);
        json.put(DbObjects.SEQUENCE_ID, nextSeqId);
        json.put(DbObjects.TIMESTAMP, timestamp);
        json.put(DbObjects.APP_ID, appId);

        // Explicit column referencing avoids database errors.
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, getNextId());
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, feedName);
        cv.put(DbObject.CONTACT_ID, Contact.MY_ID);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.SEQUENCE_ID, nextSeqId);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.TIMESTAMP, timestamp);
        cv.put(DbObject.LAST_MODIFIED_TIMESTAMP, new Date().getTime());

        if (values.containsKey(DbObject.RAW)) {
            cv.put(DbObject.RAW, values.getAsByteArray(DbObject.RAW));
        }
        if (values.containsKey(DbObject.KEY_INT)) {
            cv.put(DbObject.KEY_INT, values.getAsInteger(DbObject.KEY_INT));
        }
        if (json.has(DbObject.CHILD_FEED_NAME)) {
            cv.put(DbObject.CHILD_FEED_NAME, json.optString(DbObject.CHILD_FEED_NAME));
        }
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        Long objId = getWritableDatabase().insertOrThrow(DbObject.TABLE, null, cv);

        if (json.has(DbObjects.TARGET_HASH)) {
            long hashA = json.optLong(DbObjects.TARGET_HASH);
            long idA = objIdForHash(hashA);
            String relation;
            if (json.has(DbObjects.TARGET_RELATION)) {
                relation = json.optString(DbObjects.TARGET_RELATION);
            } else {
                relation = DbRelation.RELATION_PARENT;
            }
            if (idA == -1) {
                Log.e(TAG, "No objId found for hash " + hashA);
            } else {
                addObjRelation(idA, objId, relation);
            }
        }

        Uri objUri = DbObject.uriForObj(objId);
        mContext.getContentResolver().registerContentObserver(objUri, false,
                new ModificationObserver(mContext, objId));
        return objId;
    } catch (Exception e) {
        // TODO, too spammy
        //e.printStackTrace(System.err);
        return -1;
    }
}