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:org.opendatakit.common.android.utilities.ODKDatabaseUtils.java

private void upsertDataIntoExistingDBTable(SQLiteDatabase db, String tableId,
        ArrayList<ColumnDefinition> orderedColumns, ContentValues cvValues, boolean shouldUpdate) {
    String rowId = null;//from  w  w  w .j  a  va 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:com.tct.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  va 2s  .  c  o  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
    // TS: zhaotianyong 2015-01-27 EMAIL BUGFIX-912291 MOD_S
    if (mUnderlyingCursor.getInnerUri() != null) {
        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);
            }
        }
    }
    // TS: zhaotianyong 2015-01-27 EMAIL BUGFIX-912291 MOD_E
    return result;
}

From source file:org.opendatakit.sensors.manager.WorkerThread.java

private void parseSensorDataAndInsertIntoTable(ODKSensor aSensor, String strTableDef, Bundle dataBundle) {
    JSONObject jsonTableDef = null;// w w w. ja v a  2 s.c o  m
    ContentValues tablesValues = new ContentValues();

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(serviceContext, aSensor.getAppNameForDatabase());

        jsonTableDef = new JSONObject(strTableDef);

        String tableId = jsonTableDef.getJSONObject(ODKJsonNames.jsonTableStr)
                .getString(ODKJsonNames.jsonTableIdStr);

        if (tableId == null) {
            return;
        }

        boolean success;

        success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Exception testing for tableId " + tableId);
        }
        if (!success) {
            sensorManager.parseDriverTableDefintionAndCreateTable(aSensor.getSensorID(),
                    aSensor.getAppNameForDatabase(), db);
        }

        success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Exception testing for tableId " + tableId);
        }
        if (!success) {
            throw new SQLException("Unable to create tableId " + tableId);
        }

        ArrayList<ColumnDefinition> orderedDefs = TableUtil.get().getColumnDefinitions(db,
                aSensor.getAppNameForDatabase(), tableId);

        // Create the columns for the driver table
        for (ColumnDefinition col : orderedDefs) {
            if (!col.isUnitOfRetention()) {
                continue;
            }

            String colName = col.getElementKey();
            ElementType type = col.getType();

            if (colName.equals(DataSeries.SENSOR_ID)) {

                // special treatment
                tablesValues.put(colName, aSensor.getSensorID());

            } else if (type.getDataType() == ElementDataType.bool) {

                Boolean boolColData = dataBundle.containsKey(colName) ? dataBundle.getBoolean(colName) : null;
                Integer colData = (boolColData == null) ? null : (boolColData ? 1 : 0);
                tablesValues.put(colName, colData);

            } else if (type.getDataType() == ElementDataType.integer) {

                Integer colData = dataBundle.containsKey(colName) ? dataBundle.getInt(colName) : null;
                tablesValues.put(colName, colData);

            } else if (type.getDataType() == ElementDataType.number) {

                Double colData = dataBundle.containsKey(colName) ? dataBundle.getDouble(colName) : null;
                tablesValues.put(colName, colData);

            } else {
                // everything else is a string value coming across the wire...
                String colData = dataBundle.containsKey(colName) ? dataBundle.getString(colName) : null;
                tablesValues.put(colName, colData);
            }
        }

        if (tablesValues.size() > 0) {
            Log.i(TAG, "Writing db values for sensor:" + aSensor.getSensorID());
            String rowId = tablesValues.containsKey(DataTableColumns.ID)
                    ? tablesValues.getAsString(DataTableColumns.ID)
                    : null;
            if (rowId == null) {
                rowId = ODKDataUtils.genUUID();
            }
            ODKDatabaseUtils.get().insertDataIntoExistingDBTableWithId(db, tableId, orderedDefs, tablesValues,
                    rowId);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (db != null) {
            db.close();
        }
    }
}

From source file:com.fututel.db.DBProvider.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    int count;/*from  www .  ja  v a2s  . c om*/
    String finalWhere;
    int matched = URI_MATCHER.match(uri);

    switch (matched) {
    case ACCOUNTS:
        count = db.update(SipProfile.ACCOUNTS_TABLE_NAME, values, where, whereArgs);
        break;
    case ACCOUNTS_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipProfile.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.update(SipProfile.ACCOUNTS_TABLE_NAME, values, finalWhere, whereArgs);
        break;
    case CALLLOGS:
        count = db.update(SipManager.CALLLOGS_TABLE_NAME, values, where, whereArgs);
        break;
    case CALLLOGS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(CallLog.Calls._ID + " = " + ContentUris.parseId(uri),
                where);
        count = db.update(SipManager.CALLLOGS_TABLE_NAME, values, finalWhere, whereArgs);
        break;
    case FILTERS:
        count = db.update(SipManager.FILTERS_TABLE_NAME, values, where, whereArgs);
        break;
    case FILTERS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(Filter._ID + " = " + ContentUris.parseId(uri), where);
        count = db.update(SipManager.FILTERS_TABLE_NAME, values, finalWhere, whereArgs);
        break;
    case MESSAGES:
        count = db.update(SipMessage.MESSAGES_TABLE_NAME, values, where, whereArgs);
        break;
    case MESSAGES_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipMessage.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.update(SipMessage.MESSAGES_TABLE_NAME, values, where, whereArgs);
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            SipProfileState ps = new SipProfileState();
            if (profilesStatus.containsKey(id)) {
                ContentValues currentValues = profilesStatus.get(id);
                ps.createFromContentValue(currentValues);
            }
            ps.createFromContentValue(values);
            ContentValues cv = ps.getAsContentValue();
            cv.put(SipProfileState.ACCOUNT_ID, id);
            profilesStatus.put(id, cv);
            Log.d(THIS_FILE, "Updated " + cv);
        }
        count = 1;
        break;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);

    long rowId = -1;
    if (matched == ACCOUNTS_ID || matched == ACCOUNTS_STATUS_ID) {
        rowId = ContentUris.parseId(uri);
    }
    if (rowId >= 0) {
        if (matched == ACCOUNTS_ID) {
            // Don't broadcast if we only changed wizard or only changed priority
            boolean doBroadcast = true;
            if (values.size() == 1) {
                if (values.containsKey(SipProfile.FIELD_WIZARD)) {
                    doBroadcast = false;
                } else if (values.containsKey(SipProfile.FIELD_PRIORITY)) {
                    doBroadcast = false;
                }
            }
            if (doBroadcast) {
                broadcastAccountChange(rowId);
            }
        } else if (matched == ACCOUNTS_STATUS_ID) {
            broadcastRegistrationChange(rowId);
        }
    }
    if (matched == FILTERS || matched == FILTERS_ID) {
        Filter.resetCache();
    }

    return count;
}

From source file:net.sf.diningout.content.SyncAdapter.java

/**
 * Insert new system contacts, delete orphaned app contacts, and synchronise any changes to
 * existing./* ww w .ja  v a2  s .  c om*/
 */
private void refreshContacts(Context context, ContentProviderClient cp) throws RemoteException {
    /* get system contacts */
    String[] proj = { Email.ADDRESS, ContactsContract.Contacts.LOOKUP_KEY, RawContacts.CONTACT_ID,
            ContactsContract.Contacts.DISPLAY_NAME };
    String sel = Email.IN_VISIBLE_GROUP + " = 1 AND " + Email.ADDRESS + " <> ?";
    String[] args = { Accounts.selected().name };
    EasyCursor sys = new EasyCursor(cr().query(Email.CONTENT_URI, proj, sel, args, Email.ADDRESS));
    /* get app contacts */
    proj = new String[] { Contacts.EMAIL, Contacts.ANDROID_LOOKUP_KEY, Contacts.ANDROID_ID, Contacts.NAME, _ID,
            Contacts.FOLLOWING, Contacts.STATUS_ID };
    sel = Contacts.EMAIL + " IS NOT NULL";
    EasyCursor app = new EasyCursor(cp.query(CONTACTS_URI, proj, sel, null, Contacts.EMAIL));
    /* compare and sync */
    ContentValues vals = new ContentValues();
    for (CursorJoiner.Result result : new CursorJoiner(sys, new String[] { Email.ADDRESS }, app,
            new String[] { Contacts.EMAIL })) {
        switch (result) {
        case LEFT: // new system contact, insert into app contacts
            String email = sys.getString(Email.ADDRESS);
            String hash = BaseEncoding.base64()
                    .encode(Hashing.sha512().hashString(email.toLowerCase(ENGLISH), UTF_8).asBytes());
            long id = Contacts.idForHash(hash); // do we have this contact and not know it?
            /* insert or update values */
            vals.put(Contacts.ANDROID_LOOKUP_KEY, sys.getString(ContactsContract.Contacts.LOOKUP_KEY));
            vals.put(Contacts.ANDROID_ID, sys.getLong(RawContacts.CONTACT_ID));
            String name = sys.getString(ContactsContract.Contacts.DISPLAY_NAME);
            vals.put(Contacts.NAME, name);
            vals.put(Contacts.NORMALISED_NAME, SQLite.normalise(name));
            vals.put(Contacts.EMAIL, email);
            if (id <= 0) {
                vals.put(Contacts.EMAIL_HASH, hash);
                vals.put(Contacts.COLOR, Contacts.defaultColor());
                id = ContentUris.parseId(cp.insert(CONTACTS_URI, vals));
            } else {
                cp.update(ContentUris.withAppendedId(CONTACTS_URI, id), vals, null, null);
            }
            if (id > 0) {
                context.startService(new Intent(context, FriendColorService.class)
                        .putExtra(FriendColorService.EXTRA_ID, id));
            }
            break;
        case RIGHT: // orphaned app contact, delete unless user is following
            if (app.getInt(Contacts.FOLLOWING) == 0 && app.getInt(Contacts.STATUS_ID) == ACTIVE.id) {
                vals.put(Contacts.STATUS_ID, DELETED.id);
                vals.put(Contacts.DIRTY, 1);
                cp.update(Uris.appendId(CONTACTS_URI, app), vals, null, null);
            }
            break;
        case BOTH: // matching contacts, update details in app if needed
            String s = sys.getString(ContactsContract.Contacts.LOOKUP_KEY);
            if (!s.equals(app.getString(Contacts.ANDROID_LOOKUP_KEY))) {
                vals.put(Contacts.ANDROID_LOOKUP_KEY, s);
            }
            long l = sys.getLong(RawContacts.CONTACT_ID);
            if (l != app.getLong(Contacts.ANDROID_ID)) {
                vals.put(Contacts.ANDROID_ID, l);
            }
            s = sys.getString(ContactsContract.Contacts.DISPLAY_NAME);
            if (!s.equals(app.getString(Contacts.NAME))) {
                vals.put(Contacts.NAME, s);
                vals.put(Contacts.NORMALISED_NAME, SQLite.normalise(s));
            }
            if (app.getInt(Contacts.STATUS_ID) == DELETED.id) {
                vals.put(Contacts.STATUS_ID, ACTIVE.id);
                vals.put(Contacts.DIRTY, 1);
            }
            if (vals.size() > 0) {
                cp.update(Uris.appendId(CONTACTS_URI, app), vals, null, null);
                context.startService(new Intent(context, FriendColorService.class)
                        .putExtra(FriendColorService.EXTRA_ID, app.getLong(_ID)));
            }
            break;
        }
        vals.clear();
    }
    sys.close();
    app.close();
}

From source file:com.csipsimple.db.DBProvider.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    int count;// w  w w .jav a 2  s . c om
    String finalWhere;
    int matched = URI_MATCHER.match(uri);

    List<String> possibles = getPossibleFieldsForType(matched);
    checkSelection(possibles, where);

    switch (matched) {
    case ACCOUNTS:
        count = db.update(SipProfile.ACCOUNTS_TABLE_NAME, values, where, whereArgs);
        break;
    case ACCOUNTS_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipProfile.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.update(SipProfile.ACCOUNTS_TABLE_NAME, values, finalWhere, whereArgs);
        break;
    case CALLLOGS:
        count = db.update(SipManager.CALLLOGS_TABLE_NAME, values, where, whereArgs);
        break;
    case CALLLOGS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(CallLog.Calls._ID + " = " + ContentUris.parseId(uri),
                where);
        count = db.update(SipManager.CALLLOGS_TABLE_NAME, values, finalWhere, whereArgs);
        break;
    case FILTERS:
        count = db.update(SipManager.FILTERS_TABLE_NAME, values, where, whereArgs);
        break;
    case FILTERS_ID:
        finalWhere = DatabaseUtilsCompat.concatenateWhere(Filter._ID + " = " + ContentUris.parseId(uri), where);
        count = db.update(SipManager.FILTERS_TABLE_NAME, values, finalWhere, whereArgs);
        break;
    case MESSAGES:
        count = db.update(SipMessage.MESSAGES_TABLE_NAME, values, where, whereArgs);
        break;
    case MESSAGES_ID:
        finalWhere = DatabaseUtilsCompat
                .concatenateWhere(SipMessage.FIELD_ID + " = " + ContentUris.parseId(uri), where);
        count = db.update(SipMessage.MESSAGES_TABLE_NAME, values, where, whereArgs);
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            SipProfileState ps = new SipProfileState();
            if (profilesStatus.containsKey(id)) {
                ContentValues currentValues = profilesStatus.get(id);
                ps.createFromContentValue(currentValues);
            }
            ps.createFromContentValue(values);
            ContentValues cv = ps.getAsContentValue();
            cv.put(SipProfileState.ACCOUNT_ID, id);
            profilesStatus.put(id, cv);
            Log.d(THIS_FILE, "Updated " + cv);
        }
        count = 1;
        break;
    default:
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);

    long rowId = -1;
    if (matched == ACCOUNTS_ID || matched == ACCOUNTS_STATUS_ID) {
        rowId = ContentUris.parseId(uri);
    }
    if (rowId >= 0) {
        if (matched == ACCOUNTS_ID) {
            // Don't broadcast if we only changed wizard or only changed priority
            boolean doBroadcast = true;
            if (values.size() == 1) {
                if (values.containsKey(SipProfile.FIELD_WIZARD)) {
                    doBroadcast = false;
                } else if (values.containsKey(SipProfile.FIELD_PRIORITY)) {
                    doBroadcast = false;
                }
            }
            if (doBroadcast) {
                broadcastAccountChange(rowId);
            }
        } else if (matched == ACCOUNTS_STATUS_ID) {
            broadcastRegistrationChange(rowId);
        }
    }
    if (matched == FILTERS || matched == FILTERS_ID) {
        Filter.resetCache();
    }

    return count;
}

From source file:org.opendatakit.services.database.utlities.ODKDatabaseImplUtils.java

/**
 * Insert a row into a local only table//from   ww w .j  a  v  a 2  s  .co m
 *
 * @param db
 * @param tableId
 * @param rowValues
 * @throws ActionNotAuthorizedException
 */
public void insertLocalOnlyRow(OdkConnectionInterface db, String tableId, ContentValues rowValues)
        throws IllegalArgumentException {

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

    HashMap<String, Object> cvDataTableVal = new HashMap<String, Object>();
    for (String key : rowValues.keySet()) {
        cvDataTableVal.put(key, rowValues.get(key));
    }

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

        db.insertOrThrow(tableId, null, cvDataTableVal);

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

From source file:org.opendatakit.services.database.utlities.ODKDatabaseImplUtils.java

/**
 * Update a row in a local only table/*from   w ww.j  av a 2  s. co m*/
 *
 * @param db
 * @param tableId
 * @param rowValues
 * @param whereClause
 * @param bindArgs
 * @throws ActionNotAuthorizedException
 */
public void updateLocalOnlyRow(OdkConnectionInterface db, String tableId, ContentValues rowValues,
        String whereClause, Object[] bindArgs) throws IllegalArgumentException {

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

    HashMap<String, Object> cvDataTableVal = new HashMap<String, Object>();
    for (String key : rowValues.keySet()) {
        cvDataTableVal.put(key, rowValues.get(key));
    }

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

        db.update(tableId, cvDataTableVal, whereClause, bindArgs);

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

From source file:org.opendatakit.services.database.utlities.ODKDatabaseImplUtils.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./*w w  w .ja v  a2 s. com*/
 * <p/>
 * 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 rowId
 * @param activeUser
 * @param rolesList
 * @param locale
 */
public void insertRowWithId(OdkConnectionInterface db, String tableId, OrderedColumns orderedColumns,
        ContentValues cvValues, String rowId, String activeUser, String rolesList, String locale)
        throws ActionNotAuthorizedException {

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

    HashMap<String, Object> cvDataTableVal = new HashMap<String, Object>();
    cvDataTableVal.put(DataTableColumns.ID, rowId);
    for (String key : cvValues.keySet()) {
        cvDataTableVal.put(key, cvValues.get(key));
    }

    upsertDataIntoExistingTable(db, tableId, orderedColumns, cvDataTableVal, false, false, activeUser,
            rolesList, locale, false);
}

From source file:org.opendatakit.services.database.utlities.ODKDatabaseImplUtils.java

/**
 * Inserts a checkpoint row for the given rowId in the tableId. Checkpoint
 * rows are created by ODK Survey to hold intermediate values during the
 * filling-in of the form. They act as restore points in the Survey, should
 * the application die./* ww  w . j a v  a 2s. c o m*/
 *
 * @param db
 * @param tableId
 * @param orderedColumns
 * @param cvValues
 * @param rowId
 * @param activeUser
 * @param rolesList
 * @param locale
 */
public void insertCheckpointRowWithId(OdkConnectionInterface db, String tableId, OrderedColumns orderedColumns,
        ContentValues cvValues, String rowId, String activeUser, String rolesList, String locale)
        throws ActionNotAuthorizedException {

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

    // these are all managed in the database layer...
    // the user should NOT set them...

    if (cvValues.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)) {
        throw new IllegalArgumentException(
                t + ": No user supplied savepoint timestamp can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.SAVEPOINT_TYPE)) {
        throw new IllegalArgumentException(
                t + ": No user supplied savepoint type can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.ROW_ETAG)) {
        throw new IllegalArgumentException(t + ": No user supplied row ETag can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.SYNC_STATE)) {
        throw new IllegalArgumentException(
                t + ": No user supplied sync state can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.CONFLICT_TYPE)) {
        throw new IllegalArgumentException(
                t + ": No user supplied conflict type can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.FILTER_VALUE)) {
        throw new IllegalArgumentException(
                t + ": No user supplied filter value can be included for a checkpoint");
    }

    if (cvValues.containsKey(DataTableColumns.FILTER_TYPE)) {
        throw new IllegalArgumentException(
                t + ": No user supplied filter type can be included for a checkpoint");
    }

    // If a rowId is specified, a cursor will be needed to
    // get the current row to create a checkpoint with the relevant data
    Cursor c = null;
    try {
        // Allow the user to pass in no rowId if this is the first
        // checkpoint row that the user is adding
        if (rowId == null) {

            // TODO: is this even valid any more? I think we disallow this in the AIDL flow.

            String rowIdToUse = LocalizationUtils.genUUID();
            HashMap<String, Object> currValues = new HashMap<String, Object>();
            for (String key : cvValues.keySet()) {
                currValues.put(key, cvValues.get(key));
            }
            currValues.put(DataTableColumns._ID, rowIdToUse);
            currValues.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
            insertCheckpointIntoExistingTable(db, tableId, orderedColumns, currValues, activeUser, rolesList,
                    locale, true, null, null);
            return;
        }

        StringBuilder b = new StringBuilder();
        b.append(K_DATATABLE_ID_EQUALS_PARAM).append(S_AND).append(DataTableColumns.SAVEPOINT_TIMESTAMP)
                .append(" IN (SELECT MAX(").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(") FROM ")
                .append(tableId).append(K_WHERE).append(K_DATATABLE_ID_EQUALS_PARAM).append(")");
        c = db.query(tableId, null, b.toString(), new Object[] { rowId, rowId }, null, null, null, null);
        c.moveToFirst();

        if (c.getCount() > 1) {
            throw new IllegalStateException(t + ": More than one checkpoint at a timestamp");
        }

        // Inserting a checkpoint for the first time
        if (c.getCount() <= 0) {
            HashMap<String, Object> currValues = new HashMap<String, Object>();
            for (String key : cvValues.keySet()) {
                currValues.put(key, cvValues.get(key));
            }
            currValues.put(DataTableColumns._ID, rowId);
            currValues.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
            insertCheckpointIntoExistingTable(db, tableId, orderedColumns, currValues, activeUser, rolesList,
                    locale, true, null, null);
            return;
        } else {
            // Make sure that the conflict_type of any existing row
            // is null, otherwise throw an exception
            int conflictIndex = c.getColumnIndex(DataTableColumns.CONFLICT_TYPE);
            if (!c.isNull(conflictIndex)) {
                throw new IllegalStateException(
                        t + ":  A checkpoint cannot be added for a row that is in conflict");
            }

            HashMap<String, Object> currValues = new HashMap<String, Object>();
            for (String key : cvValues.keySet()) {
                currValues.put(key, cvValues.get(key));
            }

            // This is unnecessary
            // We should only have one row at this point
            //c.moveToFirst();

            String priorFilterType = null;
            String priorFilterValue = null;

            // Get the number of columns to iterate over and add
            // those values to the content values
            for (int i = 0; i < c.getColumnCount(); i++) {
                String name = c.getColumnName(i);

                if (currValues.containsKey(name)) {
                    continue;
                }

                // omitting savepoint timestamp will generate a new timestamp.
                if (name.equals(DataTableColumns.SAVEPOINT_TIMESTAMP)) {
                    continue;
                }

                // set savepoint type to null to mark this as a checkpoint
                if (name.equals(DataTableColumns.SAVEPOINT_TYPE)) {
                    currValues.put(name, null);
                    continue;
                }

                // sync state (a non-null field) should either remain 'new_row'
                // or be set to 'changed' for all other existing values.
                if (name.equals(DataTableColumns.SYNC_STATE)) {
                    String priorState = c.getString(i);
                    if (priorState.equals(SyncState.new_row.name())) {
                        currValues.put(name, SyncState.new_row.name());
                    } else {
                        currValues.put(name, SyncState.changed.name());
                    }
                    continue;
                }

                if (c.isNull(i)) {
                    currValues.put(name, null);
                    continue;
                }

                // otherwise, just copy the values over...
                Class<?> theClass = CursorUtils.getIndexDataType(c, i);
                Object object = CursorUtils.getIndexAsType(c, theClass, i);
                insertValueIntoContentValues(currValues, theClass, name, object);

                if (name.equals(DataTableColumns.FILTER_TYPE)) {
                    priorFilterType = c.getString(i);
                }

                if (name.equals(DataTableColumns.FILTER_VALUE)) {
                    priorFilterValue = c.getString(i);
                }
            }

            insertCheckpointIntoExistingTable(db, tableId, orderedColumns, currValues, activeUser, rolesList,
                    locale, false, priorFilterType, priorFilterValue);
        }
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }
}