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.liferay.alerts.database.DatabaseHelper.java

private void _convertMessageToJSONObject(SQLiteDatabase database) {
    StringBuilder select = new StringBuilder();

    select.append("SELECT ");
    select.append(Alert.ID);/*www. j av a2 s  .co m*/
    select.append(", ");
    select.append(Alert.PAYLOAD);
    select.append(" FROM ");
    select.append(AlertDAO.TABLE_NAME);

    Cursor cursor = database.rawQuery(select.toString(), null);

    while (cursor.moveToNext()) {
        try {
            long id = cursor.getLong(cursor.getColumnIndex(Alert.ID));
            String payload = cursor.getString(cursor.getColumnIndex(Alert.PAYLOAD));

            JSONObject jsonObject = new JSONObject();
            jsonObject.put(Alert.MESSAGE, payload);

            ContentValues values = new ContentValues();
            values.put(Alert.PAYLOAD, jsonObject.toString());

            StringBuilder sb = new StringBuilder();

            sb.append(Alert.ID);
            sb.append(CharPool.SPACE);
            sb.append("= ?");

            String whereClause = sb.toString();

            String[] whereArgs = { String.valueOf(id) };

            database.update(AlertDAO.TABLE_NAME, values, whereClause, whereArgs);
        } catch (JSONException je) {
            Log.e(_TAG, "Couldn't convert message.", je);
        }
    }
}

From source file:eu.operando.operandoapp.database.DatabaseHelper.java

public int updateDomainFilter(DomainFilter domainFilter) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_CONTENT, domainFilter.getContent().trim());
    values.put(KEY_SOURCE, domainFilter.getSource());
    values.put(KEY_WILDCARD, domainFilter.getWildcard());
    values.put(KEY_MODIFIED, getDateTime());

    // updating row
    return db.update(TABLE_DOMAIN_FILTERS, values, KEY_ID + " = ?",
            new String[] { String.valueOf(domainFilter.getId()) });
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

private void addParentIdToChildren(SQLiteDatabase tempDb, ChildArrayResults childResults, String parentId) {

    if (childResults == null || childResults.childIds == null || childResults.childIds.size() == 0) {
        return;/*from   w w  w .j  a  v  a 2 s  .c om*/
    }

    ContentValues values = new ContentValues();
    values.put("parentTopic_id", parentId);

    boolean isTopic = "Topic".equals(childResults.childKind);
    String table = isTopic ? topicTableName : videoTableName;

    StringBuilder where = new StringBuilder();
    where.append(isTopic ? "_id IN (?" : "readable_id IN (?");
    // First '?' already added, so start at 1.
    for (int i = 1; i < childResults.childIds.size(); ++i) {
        where.append(",?");
    }
    where.append(")");
    String whereClause = where.toString();

    String[] whereArg = childResults.childIds.toArray(new String[childResults.childIds.size()]);

    tempDb.update(table, values, whereClause, whereArg);
}

From source file:net.smart_json_database.JSONDatabase.java

public int update(JSONEntity entity) {
    int returnValue = -1;
    if (entity.getUid() == -1) {
        return returnValue;
    }//ww w  . j  ava2  s  .  c o m

    SQLiteDatabase db = dbHelper.getWritableDatabase();

    try {
        db.beginTransaction();
        entity.setUpdateDate(new Date());
        ContentValues values = new ContentValues();
        values.put("data", entity.getData().toString());
        values.put("updateDate", Util.DateToString(entity.getUpdateDate()));
        values.put("type", entity.getType());
        String[] params = new String[] { "" + entity.getUid() };
        db.update(TABLE_JSON_DATA, values, "json_uid = ?", params);
        for (String name : entity.getTags().getToAdd()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                tagid = insertTag(name, db);
            } else {
                tagid = tags.get(name);
            }
            if (relateTagWithJsonEntity(tagid, entity.getUid(), db) == -1) {
                throw new Exception("could not relate");
            }

        }
        for (String name : entity.getTags().getToRemove()) {
            int tagid = -1;
            if (!tags.containsKey(name)) {
                continue;
            } else {
                tagid = tags.get(name);
            }

            db.delete(TABLE_REL_TAG_JSON_DATA, "to_id = ?", new String[] { "" + tagid });
        }

        for (HasMany hasMany : entity.getHasManyRelations().values()) {
            for (Integer id : hasMany.getToRemove()) {
                deleteRelation(hasMany.getName(), entity.getUid(), id, db);
            }

            for (Integer id : hasMany.getToAdd()) {
                insertRelation(hasMany.getName(), entity.getUid(), id, db);
            }
        }

        for (BelongsTo belongsTo : entity.getBelongsToRelations().values()) {
            for (Integer id : belongsTo.getToRemove()) {
                deleteRelation(belongsTo.getName(), id, entity.getUid(), db);
            }

            for (Integer id : belongsTo.getToAdd()) {
                insertRelation(belongsTo.getName(), id, entity.getUid(), db);
            }
        }

        db.setTransactionSuccessful();
        returnValue = entity.getUid();
        notifyListenersOnEntityChange(returnValue, IDatabaseChangeListener.CHANGETYPE_UPDATE);
    } catch (Exception e) {
        returnValue = -1;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;

}

From source file:cn.edu.wyu.documentviewer.RecentsProvider.java

@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = mHelper.getWritableDatabase();
    final ContentValues key = new ContentValues();
    switch (sMatcher.match(uri)) {
    case URI_RECENT:
        values.put(RecentColumns.TIMESTAMP, System.currentTimeMillis());
        db.insert(TABLE_RECENT, null, values);
        final long cutoff = System.currentTimeMillis() - MAX_HISTORY_IN_MILLIS;
        db.delete(TABLE_RECENT, RecentColumns.TIMESTAMP + "<" + cutoff, null);
        return uri;
    case URI_STATE:
        final String authority = uri.getPathSegments().get(1);
        final String rootId = uri.getPathSegments().get(2);
        final String documentId = uri.getPathSegments().get(3);

        key.put(StateColumns.AUTHORITY, authority);
        key.put(StateColumns.ROOT_ID, rootId);
        key.put(StateColumns.DOCUMENT_ID, documentId);

        // Ensure that row exists, then update with changed values
        db.insertWithOnConflict(TABLE_STATE, null, key, SQLiteDatabase.CONFLICT_IGNORE);
        db.update(TABLE_STATE, values, StateColumns.AUTHORITY + "=? AND " + StateColumns.ROOT_ID + "=? AND "
                + StateColumns.DOCUMENT_ID + "=?", new String[] { authority, rootId, documentId });

        return uri;
    case URI_RESUME:
        values.put(ResumeColumns.TIMESTAMP, System.currentTimeMillis());

        final String packageName = uri.getPathSegments().get(1);
        key.put(ResumeColumns.PACKAGE_NAME, packageName);

        // Ensure that row exists, then update with changed values
        db.insertWithOnConflict(TABLE_RESUME, null, key, SQLiteDatabase.CONFLICT_IGNORE);
        db.update(TABLE_RESUME, values, ResumeColumns.PACKAGE_NAME + "=?", new String[] { packageName });
        return uri;
    default:/* ww  w .  j  a  v a 2s  .c o m*/
        throw new UnsupportedOperationException("Unsupported Uri " + uri);
    }
}

From source file:com.robotoworks.mechanoid.db.SQuery.java

public int update(SQLiteDatabase db, String table, ContentValues values) {
    return db.update(table, values, mBuilder.toString(), getArgsArray());
}

From source file:ru.valle.safetrade.SellActivity.java

private void savePrivateKey(final String encryptedPrivateKey) {
    final String password = tradeInfo.password;
    final long id = rowId;
    privateKeyDecodingTask = new AsyncTask<Void, String, KeyPair>() {
        public ProgressDialog progressDialog;

        @Override/*from  w ww.j av a  2s. c  o  m*/
        protected void onPreExecute() {
            final CharSequence oldEnteredValue = privateKeyView.getText();
            privateKeyView.setText(encryptedPrivateKey);
            progressDialog = ProgressDialog.show(SellActivity.this, null,
                    getString(R.string.decrypting_private_key), true);
            progressDialog.setCancelable(true);
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    privateKeyView.setText(oldEnteredValue);
                    privateKeyDecodingTask.cancel(true);
                    if (rowId != -1) {
                        loadState(rowId);
                    }
                }
            });
        }

        @Override
        protected void onProgressUpdate(String... values) {
            try {
                progressDialog.setMessage(values[0]);
            } catch (Exception ignored) {
            }
        }

        @Override
        protected KeyPair doInBackground(Void... params) {
            try {
                KeyPair keyPair = BTCUtils.bip38Decrypt(encryptedPrivateKey, password);
                if (keyPair != null) {
                    SQLiteDatabase db = DatabaseHelper.getInstance(SellActivity.this).getWritableDatabase();
                    if (db != null) {
                        ContentValues cv = new ContentValues();
                        cv.put(DatabaseHelper.COLUMN_ADDRESS, keyPair.address);
                        cv.put(DatabaseHelper.COLUMN_ENCRYPTED_PRIVATE_KEY, encryptedPrivateKey);
                        cv.put(DatabaseHelper.COLUMN_PRIVATE_KEY,
                                BTCUtils.encodeWifKey(keyPair.privateKey.isPublicKeyCompressed,
                                        BTCUtils.getPrivateKeyBytes(keyPair.privateKey.privateKeyDecoded)));
                        db.update(DatabaseHelper.TABLE_HISTORY, cv, BaseColumns._ID + "=?",
                                new String[] { String.valueOf(id) });
                    }
                }
                return keyPair;
            } catch (InterruptedException e) {
                Log.v(TAG, "pk decrypt interrupted");
                return null;
            } catch (Throwable e) {
                Log.e(TAG, "pk decrypt", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(final KeyPair keyPair) {
            try {
                progressDialog.dismiss();
            } catch (Exception ignored) {
            }
            privateKeyDecodingTask = null;
            showAlert(keyPair != null ? getString(R.string.private_key_decrypted, keyPair.address)
                    : getString(R.string.unable_to_decrypt_private_key));
            loadState(rowId);
        }
    }.execute();

}

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

public int updatePlaceState(long placeId, int state) {
    final SQLiteDatabase db = mDbHelper.getWritableDatabase();
    ContentValues args = new ContentValues();
    args.put(Places.PLACE_STATE, state);
    return db.update(Tables.PLACES, args, Places._ID + "=" + placeId, null);
}

From source file:org.akop.crosswords.Storage.java

public long write(long folderId, long puzzleId, Crossword crossword) {
    long started = SystemClock.uptimeMillis();

    StorageHelper helper = getHelper();//from   w ww  . j  a va2  s . c  o  m
    SQLiteDatabase db = helper.getWritableDatabase();
    ContentValues cv;

    try {
        cv = new ContentValues();
        cv.put(Puzzle.CLASS, crossword.getClass().getName());
        cv.put(Puzzle.SOURCE_URL, crossword.getSourceUrl());
        cv.put(Puzzle.TITLE, crossword.getTitle());
        cv.put(Puzzle.AUTHOR, crossword.getAuthor());
        cv.put(Puzzle.COPYRIGHT, crossword.getCopyright());
        cv.put(Puzzle.HASH, crossword.getHash());
        cv.put(Puzzle.SOURCE_ID, crossword.getSourceId());
        cv.put(Puzzle.FOLDER_ID, folderId);
        cv.put(Puzzle.OBJECT, mGson.toJson(crossword));
        cv.put(Puzzle.OBJECT_VERSION, 1);
        cv.put(Puzzle.LAST_UPDATED, System.currentTimeMillis());

        Long millis = null;
        if (crossword.getDate() != null) {
            millis = crossword.getDate().getMillis();
        }
        cv.put(Puzzle.DATE, millis);

        if (puzzleId != ID_NOT_FOUND) {
            db.update(Puzzle.TABLE, cv, Puzzle._ID + " = " + puzzleId, null);
        } else {
            puzzleId = db.insert(Puzzle.TABLE, null, cv);
        }
    } finally {
        db.close();
    }

    Crosswords.logv("Wrote crossword %s (%dms)", crossword.getHash(), SystemClock.uptimeMillis() - started);

    Intent outgoing = new Intent(ACTION_PUZZLE_CHANGE);
    outgoing.putExtra(INTENT_PUZZLE_ID, puzzleId);
    outgoing.putExtra(INTENT_PUZZLE_URL, crossword.getSourceUrl());

    sendLocalBroadcast(outgoing);

    return puzzleId;
}

From source file:org.frc836.database.DB.java

private void insertOrUpdate(String table, String nullColumnHack, ContentValues values, String idColumnName,
        String whereClause, String[] whereArgs) {
    synchronized (ScoutingDBHelper.lock) {
        SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

        String[] projection = { idColumnName };

        Cursor c = db.query(table, projection, whereClause, whereArgs, null, null, null, "0,1");
        try {//from www . j  av  a2s.  c o  m
            if (c.moveToFirst()) {
                String[] id = { c.getString(c.getColumnIndexOrThrow(idColumnName)) };
                values.put(COLUMN_NAME_TIMESTAMP, dateParser.format(new Date()));
                db.update(table, values, idColumnName + "=?", id);
            } else {
                db.insert(table, nullColumnHack, values);
            }
        } finally {
            if (c != null)
                c.close();
            ScoutingDBHelper.getInstance().close();
        }
    }
}