Example usage for android.database.sqlite SQLiteDatabase replace

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

Introduction

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

Prototype

public long replace(String table, String nullColumnHack, ContentValues initialValues) 

Source Link

Document

Convenience method for replacing a row in the database.

Usage

From source file:Main.java

public static final int setBulkInsert(Context context, String table, SQLiteDatabase myDb,
        ContentValues[] values) {//  w  w  w  .  j av a  2  s .  c  om

    int returnCount = 0;

    try {

        for (ContentValues value : values) {

            final long _id = myDb.replace(table, null, value);

            if (_id != -1)
                returnCount++;
        }

        myDb.setTransactionSuccessful();

    } finally {
        myDb.endTransaction();
    }

    return returnCount;
}

From source file:cn.figo.mydemo.content.RecentMediaStorage.java

public void save(ContentValues contentValue) {
    OpenHelper openHelper = new OpenHelper(mAppContext);
    SQLiteDatabase db = openHelper.getWritableDatabase();
    db.replace(Entry.TABLE_NAME, null, contentValue);
}

From source file:pl.selvin.android.syncframework.content.TableInfo.java

@SuppressLint("NewApi")
final public void SyncJSON(final HashMap<String, Object> hval, final Metadata meta, final SQLiteDatabase db) {
    int i = 0;/*w  ww  .  j a v a2s.c  o  m*/
    vals.clear();
    for (; i < columns.length; i++) {
        String column = columns[i].name;
        switch (columns[i].type) {
        case ColumnType.BLOB:
            final String str = (String) hval.get(column);
            if (str != null)
                vals.put(column, Base64.decode(str, Base64.DEFAULT));
            break;
        case ColumnType.BOOLEAN:
        case ColumnType.INTEGER:
            vals.put(column, (Long) hval.get(column));
            break;
        case ColumnType.DATETIME:
            String date = (String) hval.get(column);
            if (date != null) {
                date = sdf.format(new Date(Long.parseLong(date.substring(6, date.length() - 2))));
            }
            vals.put(column, date);
            break;
        case ColumnType.NUMERIC:
            Object obj = hval.get(column);
            if (obj instanceof Double)
                vals.put(column, (Double) obj);
            else
                vals.put(column, (Long) obj);
            break;
        default:
            vals.put(column, (String) hval.get(column));
            break;
        }
    }
    vals.put(_.uri, meta.uri);
    vals.put(_.tempId, (String) null);
    vals.put(_.isDirty, 0);
    if (meta.tempId != null) {
        db.update(name, vals, _.tempIdP, new String[] { meta.tempId });
    } else {
        db.replace(name, null, vals);
    }
}

From source file:io.vit.vitio.Managers.ConnectDatabase.java

public void saveCourses(List<Course> courses) {
    try {//from  w w w.  j av  a2  s  . c  o  m
        SQLiteDatabase db = this.getWritableDatabase();

        for (int i = 0; i < courses.size(); i++) {
            Course course = courses.get(i);

            ContentValues values = new ContentValues();

            values.put(COLUMNS[0], course.getCLASS_NUMBER());
            values.put(COLUMNS[1], course.getCOURSE_TITLE());
            values.put(COLUMNS[2], course.getCOURSE_SLOT());
            values.put(COLUMNS[3], course.getCOURSE_TYPE());
            values.put(COLUMNS[4], course.getCOURSE_TYPE_SHORT());
            Log.d("type", course.getCOURSE_TYPE_SHORT());
            values.put(COLUMNS[5], course.getCOURSE_LTPC().toString());
            values.put(COLUMNS[6], course.getCOURSE_CODE());
            values.put(COLUMNS[7], course.getCOURSE_MODE());
            values.put(COLUMNS[8], course.getCOURSE_OPTION());
            values.put(COLUMNS[9], course.getCOURSE_VENUE());
            values.put(COLUMNS[10], course.getCOURSE_FACULTY().toString());
            values.put(COLUMNS[11], course.getCOURSE_REGISTRATIONSTATUS());
            values.put(COLUMNS[12], course.getCOURSE_BILL_DATE());
            values.put(COLUMNS[13], course.getCOURSE_BILL_NUMBER());
            values.put(COLUMNS[14], course.getCOURSE_PROJECT_TITLE());
            values.put(COLUMNS[15], course.getCOURSE_JSON().toString());
            values.put(COLUMNS[16], course.getCOURSE_ATTENDANCE().getJson().toString());
            values.put(COLUMNS[17], course.getCOURSE_JSON().getJSONArray("timings").toString());
            values.put(COLUMNS[18], course.getCOURSE_JSON().getJSONObject("marks").toString());
            //db.insertWithOnConflict(TABLE_COURSES, null, values, SQLiteDatabase.CONFLICT_REPLACE);
            if (check()) {
                Log.d("update", "check()");
                //onUpgrade(db,db.getVersion(),192564);
                db.replace(TABLE_COURSES, null, values);
                //db.update(TABLE_COURSES, values, null, null);
            } else {
                Log.d("insert", "check()");
                db.insert(TABLE_COURSES, null, values);
            }
        }
        db.close();
    } catch (Exception e) {
        e.printStackTrace();
        SQLiteDatabase _db = this.getWritableDatabase();
        if (_db != null && _db.isOpen()) {
            _db.close();
        }
    }

}

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

/**
 * Insert or update a single table-level metadata KVS entry.
 * //  w  w  w  .  j  a v  a2 s  .  com
 * @param db
 * @param entry
 */
public void replaceDBTableMetadata(SQLiteDatabase db, KeyValueStoreEntry entry) {
    ContentValues values = new ContentValues();
    values.put(KeyValueStoreColumns.TABLE_ID, entry.tableId);
    values.put(KeyValueStoreColumns.PARTITION, entry.partition);
    values.put(KeyValueStoreColumns.ASPECT, entry.aspect);
    values.put(KeyValueStoreColumns.VALUE_TYPE, entry.type);
    values.put(KeyValueStoreColumns.VALUE, entry.value);
    values.put(KeyValueStoreColumns.KEY, entry.key);

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }
        db.replace(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null, values);
        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

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

/**
 * Insert or update a list of table-level metadata KVS entries. If clear is
 * true, then delete the existing set of values for this tableId before
 * inserting the new values.//from  ww  w .  j a va  2s  . com
 * 
 * @param db
 * @param tableId
 * @param metadata
 *          a List<KeyValueStoreEntry>
 * @param clear
 *          if true then delete the existing set of values for this tableId
 *          before inserting the new ones.
 */
public void replaceDBTableMetadata(SQLiteDatabase db, String tableId, List<KeyValueStoreEntry> metadata,
        boolean clear) {

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

        if (clear) {
            db.delete(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, KeyValueStoreColumns.TABLE_ID + "=?",
                    new String[] { tableId });
        }
        for (KeyValueStoreEntry e : metadata) {
            ContentValues values = new ContentValues();
            if (!tableId.equals(e.tableId)) {
                throw new IllegalArgumentException(
                        "updateDBTableMetadata: expected all kvs entries to share the same tableId");
            }
            if (e.value == null || e.value.trim().length() == 0) {
                deleteDBTableMetadata(db, e.tableId, e.partition, e.aspect, e.key);
            } else {
                values.put(KeyValueStoreColumns.TABLE_ID, e.tableId);
                values.put(KeyValueStoreColumns.PARTITION, e.partition);
                values.put(KeyValueStoreColumns.ASPECT, e.aspect);
                values.put(KeyValueStoreColumns.KEY, e.key);
                values.put(KeyValueStoreColumns.VALUE_TYPE, e.type);
                values.put(KeyValueStoreColumns.VALUE, e.value);
                db.replace(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME, null, values);
            }
        }

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

From source file:pl.selvin.android.syncframework.content.BaseContentProvider.java

protected boolean Sync(String service, String scope, String params) {
    final Date start = new Date();
    boolean hasError = false;
    if (params == null)
        params = "";
    final SQLiteDatabase db = mDB.getWritableDatabase();
    final ArrayList<TableInfo> notifyTableInfo = new ArrayList<TableInfo>();

    final String download = String.format(contentHelper.DOWNLOAD_SERVICE_URI, service, scope, params);
    final String upload = String.format(contentHelper.UPLOAD_SERVICE_URI, service, scope, params);
    final String scopeServerBlob = String.format("%s.%s.%s", service, scope, _.serverBlob);
    String serverBlob = null;//from  w w w.  j a  v a2 s  . co m
    Cursor cur = db.query(BlobsTable.NAME, new String[] { BlobsTable.C_VALUE }, BlobsTable.C_NAME + "=?",
            new String[] { scopeServerBlob }, null, null, null);
    final String originalBlob;
    if (cur.moveToFirst()) {
        originalBlob = serverBlob = cur.getString(0);
    } else {
        originalBlob = null;
    }
    cur.close();
    db.beginTransaction();
    try {
        boolean nochanges = false;
        if (serverBlob != null) {
            nochanges = !contentHelper.hasDirtTable(db, scope);
        }
        boolean resolve = false;
        final Metadata meta = new Metadata();
        final HashMap<String, Object> vals = new HashMap<String, Object>();
        final ContentValues cv = new ContentValues(2);
        JsonFactory jsonFactory = new JsonFactory();
        JsonToken current = null;
        String name = null;
        boolean moreChanges = false;
        boolean forceMoreChanges = false;
        do {
            final int requestMethod;
            final String serviceRequestUrl;
            final ContentProducer contentProducer;

            if (serverBlob != null) {
                requestMethod = HTTP_POST;
                if (nochanges) {
                    serviceRequestUrl = download;
                } else {
                    serviceRequestUrl = upload;
                    forceMoreChanges = true;
                }
                contentProducer = new SyncContentProducer(jsonFactory, db, scope, serverBlob, !nochanges,
                        notifyTableInfo, contentHelper);
                nochanges = true;
            } else {
                requestMethod = HTTP_GET;
                serviceRequestUrl = download;
                contentProducer = null;

            }
            if (moreChanges) {
                db.beginTransaction();
            }

            Result result = executeRequest(requestMethod, serviceRequestUrl, contentProducer);
            if (result.getStatus() == HttpStatus.SC_OK) {
                final JsonParser jp = jsonFactory.createParser(result.getInputStream());

                jp.nextToken(); // skip ("START_OBJECT(d) expected");
                jp.nextToken(); // skip ("FIELD_NAME(d) expected");
                if (jp.nextToken() != JsonToken.START_OBJECT)
                    throw new Exception("START_OBJECT(d - object) expected");
                while (jp.nextToken() != JsonToken.END_OBJECT) {
                    name = jp.getCurrentName();
                    if (_.__sync.equals(name)) {
                        current = jp.nextToken();
                        while (jp.nextToken() != JsonToken.END_OBJECT) {
                            name = jp.getCurrentName();
                            current = jp.nextToken();
                            if (_.serverBlob.equals(name)) {
                                serverBlob = jp.getText();
                            } else if (_.moreChangesAvailable.equals(name)) {
                                moreChanges = jp.getBooleanValue() || forceMoreChanges;
                                forceMoreChanges = false;
                            } else if (_.resolveConflicts.equals(name)) {
                                resolve = jp.getBooleanValue();
                            }
                        }
                    } else if (_.results.equals(name)) {
                        if (jp.nextToken() != JsonToken.START_ARRAY)
                            throw new Exception("START_ARRAY(results) expected");
                        while (jp.nextToken() != JsonToken.END_ARRAY) {
                            meta.isDeleted = false;
                            meta.tempId = null;
                            vals.clear();
                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                name = jp.getCurrentName();
                                current = jp.nextToken();
                                if (current == JsonToken.VALUE_STRING) {
                                    vals.put(name, jp.getText());
                                } else if (current == JsonToken.VALUE_NUMBER_INT) {
                                    vals.put(name, jp.getLongValue());
                                } else if (current == JsonToken.VALUE_NUMBER_FLOAT) {
                                    vals.put(name, jp.getDoubleValue());
                                } else if (current == JsonToken.VALUE_FALSE) {
                                    vals.put(name, 0L);
                                } else if (current == JsonToken.VALUE_TRUE) {
                                    vals.put(name, 1L);
                                } else if (current == JsonToken.VALUE_NULL) {
                                    vals.put(name, null);
                                } else {
                                    if (current == JsonToken.START_OBJECT) {
                                        if (_.__metadata.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.uri.equals(name)) {
                                                    meta.uri = jp.getText();
                                                } else if (_.type.equals(name)) {
                                                    meta.type = jp.getText();
                                                } else if (_.isDeleted.equals(name)) {
                                                    meta.isDeleted = jp.getBooleanValue();
                                                } else if (_.tempId.equals(name)) {
                                                    meta.tempId = jp.getText();
                                                }
                                            }
                                        } else if (_.__syncConflict.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                                if (_.isResolved.equals(name)) {
                                                } else if (_.conflictResolution.equals(name)) {
                                                } else if (_.conflictingChange.equals(name)) {
                                                    while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                        name = jp.getCurrentName();
                                                        current = jp.nextToken();
                                                        if (current == JsonToken.START_OBJECT) {
                                                            if (_.__metadata.equals(name)) {
                                                                while (jp.nextToken() != JsonToken.END_OBJECT) {

                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                            // resolve conf

                                        } else if (_.__syncError.equals(name)) {
                                            while (jp.nextToken() != JsonToken.END_OBJECT) {
                                                name = jp.getCurrentName();
                                                jp.nextToken();
                                            }
                                        }
                                    }
                                }
                            }
                            TableInfo tab = contentHelper.getTableFromType(meta.type);
                            if (meta.isDeleted) {
                                tab.DeleteWithUri(meta.uri, db);
                            } else {
                                tab.SyncJSON(vals, meta, db);
                            }
                            if (!notifyTableInfo.contains(tab))
                                notifyTableInfo.add(tab);
                        }
                    }
                }
                jp.close();
                if (!hasError) {
                    cv.clear();
                    cv.put(BlobsTable.C_NAME, scopeServerBlob);
                    cv.put(BlobsTable.C_VALUE, serverBlob);
                    cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
                    cv.put(BlobsTable.C_STATE, 0);
                    db.replace(BlobsTable.NAME, null, cv);
                    db.setTransactionSuccessful();
                    db.endTransaction();
                    if (DEBUG) {
                        Log.d(TAG, "CP-Sync: commit changes");
                    }
                    final ContentResolver cr = getContext().getContentResolver();
                    for (TableInfo t : notifyTableInfo) {
                        final Uri nu = contentHelper.getDirUri(t.name, false);
                        cr.notifyChange(nu, null, false);
                        // false - do not force sync cause we are in sync
                        if (DEBUG) {
                            Log.d(TAG, "CP-Sync: notifyChange table: " + t.name + ", uri: " + nu);
                        }

                        for (String n : t.notifyUris) {
                            cr.notifyChange(Uri.parse(n), null, false);
                            if (DEBUG) {
                                Log.d(TAG, "+uri: " + n);
                            }
                        }
                    }
                    notifyTableInfo.clear();
                }
            } else {
                if (DEBUG) {
                    Log.e(TAG, "Server error in fetching remote contacts: " + result.getStatus());
                }
                hasError = true;
                break;
            }
        } while (moreChanges);
    } catch (final ConnectTimeoutException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ConnectTimeoutException", e);
        }
    } catch (final IOException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    } catch (final ParseException e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    } catch (final Exception e) {
        hasError = true;
        if (DEBUG) {
            Log.e(TAG, "ParseException", e);
        }
    }
    if (hasError) {
        db.endTransaction();
        ContentValues cv = new ContentValues();
        cv.put(BlobsTable.C_NAME, scopeServerBlob);
        cv.put(BlobsTable.C_VALUE, originalBlob);
        cv.put(BlobsTable.C_DATE, Calendar.getInstance().getTimeInMillis());
        cv.put(BlobsTable.C_STATE, -1);
        db.replace(BlobsTable.NAME, null, cv);
    }
    /*-if (!hasError) {
    final ContentValues cv = new ContentValues(2);
     cv.put(BlobsTable.C_NAME, scopeServerBlob);
     cv.put(BlobsTable.C_VALUE, serverBlob);
     db.replace(BlobsTable.NAME, null, cv);
     db.setTransactionSuccessful();
    }
    db.endTransaction();
    if (!hasError) {
     for (String t : notifyTableInfo) {
    getContext().getContentResolver().notifyChange(getDirUri(t),
          null);
     }
    }*/
    if (DEBUG) {
        Helpers.LogInfo(start);
    }
    return !hasError;
}