Example usage for android.database.sqlite SQLiteDatabase update

List of usage examples for android.database.sqlite SQLiteDatabase update

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase update.

Prototype

public int update(String table, ContentValues values, String whereClause, String[] whereArgs) 

Source Link

Document

Convenience method for updating rows in the database.

Usage

From source file:com.money.manager.ex.MmxContentProvider.java

@Override
public int update(@NonNull Uri uri, ContentValues values, String whereClause, String[] whereArgs) {
    Timber.d("Update Uri: %s", uri);

    Object ret = getObjectFromUri(uri);

    initializeDependencies();//from   w w  w .  j  ava  2  s.c  o  m

    SQLiteDatabase database = openHelper.get().getWritableDatabase();

    int rowsUpdate = 0;

    if (Dataset.class.isInstance(ret)) {
        Dataset dataset = ((Dataset) ret);
        switch (dataset.getType()) {
        case TABLE:
            logUpdate(dataset, values, whereClause, whereArgs);

            try {
                rowsUpdate = database.update(dataset.getSource(), values, whereClause, whereArgs);
            } catch (Exception ex) {
                Timber.e(ex, "updating: %s", "update");
            }
            break;
        default:
            throw new IllegalArgumentException("Type of dataset not supported for update");
        }
    } else {
        throw new IllegalArgumentException("Object ret of mapContent is not istance of dataset");
    }

    if (rowsUpdate > 0) {
        notifyChange(uri);
    }

    // return rows modified
    return rowsUpdate;
}

From source file:at.bitfire.nophonespam.CallReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent.getAction()) && intent
            .getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)) {
        String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
        Log.i(TAG, "Received call: " + incomingNumber);

        Settings settings = new Settings(context);
        if (TextUtils.isEmpty(incomingNumber)) {
            // private number (no caller ID)
            if (settings.blockHiddenNumbers())
                rejectCall(context, null);

        } else {/*  ww w  .  j ava  2s .  c  om*/
            DbHelper dbHelper = new DbHelper(context);
            try {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                Cursor c = db.query(Number._TABLE, null, "? LIKE " + Number.NUMBER,
                        new String[] { incomingNumber }, null, null, null);
                if (c.moveToNext()) {
                    ContentValues values = new ContentValues();
                    DatabaseUtils.cursorRowToContentValues(c, values);
                    Number number = Number.fromValues(values);

                    rejectCall(context, number);

                    values.clear();
                    values.put(Number.LAST_CALL, System.currentTimeMillis());
                    values.put(Number.TIMES_CALLED, number.timesCalled + 1);
                    db.update(Number._TABLE, values, Number.NUMBER + "=?", new String[] { number.number });

                    BlacklistObserver.notifyUpdated();
                }
                c.close();
            } finally {
                dbHelper.close();
            }
        }
    }
}

From source file:de.nware.app.hsDroid.provider.onlineService2Provider.java

@Override
public int update(Uri uri, ContentValues values, String whereClause, String[] whereArgs) {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    int count;//from ww w. j  a  va  2s  .  com
    switch (mUriMatcher.match(uri)) {
    case EXAMS:
        count = db.update(mOpenHelper.getTableName(), values, whereClause, whereArgs);
        break;

    default:
        throw new IllegalArgumentException("Unbekannte URI " + uri);
    }
    getContext().getContentResolver().notifyChange(uri, null); // Observer?
    return count;
}

From source file:com.osfans.trime.DictionaryHelper.java

private boolean importSchema(InputStream is) {
    boolean success = false;
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();//from  w  w w  .j  ava 2s  .c om
    try {
        Yaml yaml = new Yaml();
        Map<String, Object> y = (Map<String, Object>) (yaml.load(is));
        Map<String, Object> m = (Map<String, Object>) y.get("schema");
        String schema_id = (String) m.get("schema_id");
        String name = (String) m.get("name");
        String full = yaml.dump(y);
        is.close();

        ContentValues initialValues = new ContentValues();
        initialValues.put("schema_id", schema_id);
        initialValues.put("name", name);
        initialValues.put("full", full);

        long r = db.update("schema", initialValues, "schema_id = ?", new String[] { schema_id });
        if (r == 0)
            r = db.insert("schema", null, initialValues);
        db.setTransactionSuccessful();
        success = true;
    } catch (Exception e) {
        throw new RuntimeException("Error import schema", e);
    } finally {
        db.endTransaction();
    }
    return success;
}

From source file:syncthing.android.settings.AppSettings.java

public void removeCredentials(Credentials creds) {
    SQLiteDatabase _db = db.getWritableDatabase();
    Cursor c = null;// w ww  .ja  v a  2s  .  c  o  m
    try {
        _db.beginTransaction();
        _db.delete(CredentialsDB.SCHEMA.TABLE, credentialsDeviceIdSel, new String[] { creds.id });
        c = _db.query(CredentialsDB.SCHEMA.TABLE, idCols, credentialsDefaultSel, null, null, null, null);
        if (c != null && c.getCount() == 0) {
            c.close();
            //no default set a new one
            c = _db.query(CredentialsDB.SCHEMA.TABLE, idCols, null, null, null, null, null);
            if (c != null && c.moveToFirst()) {
                ContentValues cv = new ContentValues();
                cv.put(CredentialsDB.SCHEMA.DEFAULT, 1);
                _db.update(CredentialsDB.SCHEMA.TABLE, cv, idSel, new String[] { c.getString(0) });
            }
        }
        _db.setTransactionSuccessful();
    } finally {
        _db.endTransaction();
        if (c != null)
            c.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   w w w . j  a v  a 2 s .co m*/
    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:org.thomnichols.android.gmarks.GmarksProvider.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    int count;/*from  w  w  w . j  a  v  a2  s. c  om*/
    switch (sUriMatcher.match(uri)) {
    case BOOKMARKS_URI:
        count = db.update(BOOKMARKS_TABLE_NAME, values, where, whereArgs);
        break;

    case BOOKMARK_ID_URI:
        String noteId = uri.getPathSegments().get(1);
        count = db.update(BOOKMARKS_TABLE_NAME, values,
                Bookmark.Columns._ID + "=" + noteId + (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""),
                whereArgs);
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    getContext().getContentResolver().notifyChange(uri, null);
    return count;
}

From source file:com.cloudmine.api.db.RequestDBOpenHelper.java

/**
 * Load all of the unsynced requests, and set their status to in progress.
 * @return//from w ww .  j  a  v a2 s .c  om
 */
private Cursor loadRequestTableContentsForUpdating() {
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
        String[] unsychronizedSelectionArgs = { UNSYCHRONIZED.toString() };
        Cursor cursor = db.query(BOTH_DATABASE_TABLE_JOIN, RESULTS_COLUMNS, SYNCHRONIZED_VALUE_WHERE,
                unsychronizedSelectionArgs, null, null, requestColumn(KEY_REQUEST_ID));
        cursor.getCount(); //For some reason, accessing the cursor count before performing the update is required for the load to work. Doesn't make much sense unless it is ignoring order.
        ContentValues updatedValues = getUpdateSynchronizedContentValues(IN_PROGRESS);
        db.update(REQUEST_DATABASE_TABLE, updatedValues, SYNCHRONIZED_VALUE_WHERE, unsychronizedSelectionArgs);

        db.setTransactionSuccessful();

        return cursor;
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        db.endTransaction();
    }
}

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

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

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }//from   w w  w.  j  a  v a 2 s  . c o m

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

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    /*
     * First, find out what records match this query, and if they refer to two
     * or more (formId,formVersion) tuples, then be sure to remove all
     * FORM_MEDIA_PATH references. Otherwise, if they are all for the same
     * tuple, and the update specifies a FORM_MEDIA_PATH, move all the
     * non-matching directories elsewhere.
     */
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    boolean multiset = false;
    Cursor c = null;
    try {
        c = this.query(uri, null, whereId, whereIdArgs, null);
        if (c == null) {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row did not return a cursor");
        }
        if (c.getCount() >= 1) {
            FormIdVersion ref = null;
            c.moveToPosition(-1);
            while (c.moveToNext()) {
                idValue = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class,
                        c.getColumnIndex(FormsColumns._ID));
                tableIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                formIdValue = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String tableId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.TABLE_ID));
                String formId = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_ID));
                String formVersion = ODKDatabaseUtils.get().getIndexAsString(c,
                        c.getColumnIndex(FormsColumns.FORM_VERSION));
                FormIdVersion cur = new FormIdVersion(tableId, formId, formVersion);

                int appRelativeMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                String mediaPath = ODKDatabaseUtils.get().getIndexAsString(c, appRelativeMediaPathIdx);
                if (mediaPath != null) {
                    mediaDirs.put(ODKFileUtils.asAppFile(appName, mediaPath),
                            (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
                }

                if (ref != null && !ref.equals(cur)) {
                    multiset = true;
                    break;
                } else {
                    ref = cur;
                }
            }
        }
    } catch (Exception e) {
        log.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }

    if (multiset) {
        // don't let users manually update media path
        // we are referring to two or more (formId,formVersion) tuples.
        if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
            values.remove(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
        }
    } else if (values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        // we are not a multiset and we are setting the media path
        // try to move all the existing non-matching media paths to
        // somewhere else...
        File mediaPath = ODKFileUtils.asAppFile(appName,
                values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));
        for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
            File altPath = entry.getKey();
            if (!altPath.equals(mediaPath)) {
                try {
                    moveDirectory(appName, entry.getValue(), altPath);
                } catch (IOException e) {
                    e.printStackTrace();
                    log.e(t, "Attempt to move " + altPath.getAbsolutePath() + " failed: " + e.toString());
                }
            }
        }
        // OK. we have moved the existing form definitions elsewhere. We can
        // proceed with update...
    }

    // ensure that all values are correct and ignore some user-supplied
    // values...
    patchUpValues(appName, values);

    // Make sure that the necessary fields are all set
    if (values.containsKey(FormsColumns.DATE) == true) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    SQLiteDatabase db = null;
    int count;
    try {
        // OK Finally, now do the update...
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.update(DatabaseConstants.FORMS_TABLE_NAME, values, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform update " + uri);
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:org.kontalk.provider.UsersProvider.java

private int updateUser(ContentValues values, boolean offline, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    int rc = db.update(offline ? TABLE_USERS_OFFLINE : TABLE_USERS, values, selection, selectionArgs);
    if (rc == 0) {
        ContentValues insertValues = new ContentValues(values);
        // insert new record
        insertValues.put(Users.JID, selectionArgs[0]);
        insertValues.put(Users.NUMBER, selectionArgs[0]);
        /*//from   w  w w . j  av a 2 s . c o  m
        if (!values.containsKey(Users.DISPLAY_NAME))
        insertValues.put(Users.DISPLAY_NAME, selectionArgs[0]);
         */
        insertValues.put(Users.REGISTERED, true);

        try {
            db.insert(offline ? TABLE_USERS_OFFLINE : TABLE_USERS, null, insertValues);
            return 1;
        } catch (SQLiteConstraintException e) {
            // nothing was updated but the row exists
            return 0;
        }
    }

    return rc;
}