Example usage for android.database.sqlite SQLiteDatabase insertOrThrow

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

Introduction

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

Prototype

public long insertOrThrow(String table, String nullColumnHack, ContentValues values) throws SQLException 

Source Link

Document

Convenience method for inserting a row into the database.

Usage

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

long insertGroupMember(SQLiteDatabase db, ContentValues cv) {
    try {// w ww.ja v  a 2s .co  m
        return db.insertOrThrow(GroupMember.TABLE, null, cv);
    } catch (Exception e) {
        // TODO, too spammy
        //e.printStackTrace(System.err);
        return -1;
    }
}

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

long insertGroup(SQLiteDatabase db, ContentValues cv) {
    try {/* www.  j  av a 2 s .c om*/
        validate(cv.getAsString(Group.NAME));
        return db.insertOrThrow(Group.TABLE, null, cv);
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        return -1;
    }
}

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

long insertSubscriber(SQLiteDatabase db, ContentValues cv) {
    try {//  w  w w . jav a 2s  . c o  m
        String feedName = cv.getAsString(Subscriber.FEED_NAME);
        validate(feedName);
        return db.insertOrThrow(Subscriber.TABLE, null, cv);
    } catch (SQLiteConstraintException e) {
        //this inserts dupes, so hide this spam in a way 
        //that doesn't require api level 8
        return -1;
    } catch (Exception e) {
        Log.e(TAG, e.getMessage(), e);
        return -1;
    }
}

From source file:org.pixmob.freemobile.netstat.SyncService.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<DailyStat>(15);
    final Set<Long> uploadedStats = new HashSet<Long>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor c = db.query("daily_stat", new String[] { "stat_timestamp", "orange", "free_mobile", "sync" },
            "stat_timestamp>=? AND stat_timestamp<?",
            new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
    try {/*from   w w  w.  jav a  2s.  c  o m*/
        while (c.moveToNext()) {
            final long d = c.getLong(0);
            final int sync = c.getInt(3);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = c.getInt(1);
                s.freeMobile = c.getInt(2);
                stats.put(d, s);
            }
        }
    } finally {
        c.close();
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncService.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}

From source file:com.jefftharris.passwdsafe.NotificationMgr.java

/** Update the notification expirations for a password file */
private void doUpdatePasswdFileData(long uriId, PasswdFileData fileData, SQLiteDatabase db)
        throws SQLException {
    PasswdSafeUtil.dbginfo(TAG, "Update %s, id: %d", fileData.getUri(), uriId);

    TreeMap<ExpiryEntry, Long> entries = new TreeMap<>();
    Cursor cursor = db.query(DB_TABLE_EXPIRYS,
            new String[] { DB_COL_EXPIRYS_ID, DB_COL_EXPIRYS_UUID, DB_COL_EXPIRYS_TITLE, DB_COL_EXPIRYS_GROUP,
                    DB_COL_EXPIRYS_EXPIRE },
            DB_MATCH_EXPIRYS_URI, new String[] { Long.toString(uriId) }, null, null, null);
    try {/*w  w w.j a v a2  s.  co  m*/
        while (cursor.moveToNext()) {
            ExpiryEntry entry = new ExpiryEntry(cursor.getString(1), cursor.getString(2), cursor.getString(3),
                    cursor.getLong(4));
            entries.put(entry, cursor.getLong(0));
        }
    } finally {
        cursor.close();
    }

    boolean dbchanged = false;
    ContentValues values = null;
    for (PasswdRecord rec : fileData.getPasswdRecords()) {
        PasswdExpiration expiry = rec.getPasswdExpiry();
        if (expiry == null) {
            continue;
        }

        PwsRecord pwsrec = rec.getRecord();
        ExpiryEntry entry = new ExpiryEntry(rec.getUUID(), fileData.getTitle(pwsrec), fileData.getGroup(pwsrec),
                expiry.itsExpiration.getTime());
        if (entries.remove(entry) == null) {
            if (values == null) {
                values = new ContentValues();
                values.put(DB_COL_EXPIRYS_URI, uriId);
            }
            values.put(DB_COL_EXPIRYS_UUID, entry.itsUuid);
            values.put(DB_COL_EXPIRYS_TITLE, entry.itsTitle);
            values.put(DB_COL_EXPIRYS_GROUP, entry.itsGroup);
            values.put(DB_COL_EXPIRYS_EXPIRE, entry.itsExpiry);
            db.insertOrThrow(DB_TABLE_EXPIRYS, null, values);
            dbchanged = true;
        }
    }

    for (Long rmId : entries.values()) {
        db.delete(DB_TABLE_EXPIRYS, DB_MATCH_EXPIRYS_ID, new String[] { rmId.toString() });
        dbchanged = true;
    }

    if (dbchanged) {
        loadEntries(db);
    }
}

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

private void generateAndStorePersonalInfo(SQLiteDatabase db) {
    String email = getUserEmail();
    String name = email; // How to get this?

    KeyPair keypair = DBIdentityProvider.generateKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();
    String pubKeyStr = FastBase64.encodeToString(publicKey.getEncoded());
    String privKeyStr = FastBase64.encodeToString(privateKey.getEncoded());
    ContentValues cv = new ContentValues();
    cv.put(MyInfo.PUBLIC_KEY, pubKeyStr);
    cv.put(MyInfo.PRIVATE_KEY, privKeyStr);
    cv.put(MyInfo.NAME, name);/*from  w w  w  .j  a v  a  2 s.c o  m*/
    cv.put(MyInfo.EMAIL, email);
    db.insertOrThrow(MyInfo.TABLE, null, cv);
    Log.d(TAG, "Generated public key: " + pubKeyStr);
    Log.d(TAG, "Generated priv key: **************");
}

From source file:org.totschnig.myexpenses.provider.TransactionDatabase.java

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(DATABASE_CREATE);//  ww w.  j ava  2  s  .  co m
    db.execSQL(PAYEE_CREATE);
    db.execSQL(PAYMENT_METHODS_CREATE);
    db.execSQL(TEMPLATE_CREATE);
    db.execSQL(PLAN_INSTANCE_STATUS_CREATE);
    String viewTransactions = buildViewDefinition(TABLE_TRANSACTIONS);
    db.execSQL("CREATE VIEW " + VIEW_COMMITTED + viewTransactions + " WHERE " + KEY_STATUS + " != "
            + STATUS_UNCOMMITTED + ";");
    db.execSQL("CREATE VIEW " + VIEW_UNCOMMITTED + viewTransactions + " WHERE " + KEY_STATUS + " = "
            + STATUS_UNCOMMITTED + ";");
    db.execSQL("CREATE VIEW " + VIEW_ALL + viewTransactions);
    db.execSQL("CREATE VIEW " + VIEW_TEMPLATES + buildViewDefinition(TABLE_TEMPLATES));
    db.execSQL(CATEGORIES_CREATE);
    db.execSQL(ACCOUNTS_CREATE);
    db.execSQL("CREATE VIEW " + VIEW_EXTENDED + buildViewDefinitionExtended(TABLE_TRANSACTIONS) + " WHERE "
            + KEY_STATUS + " != " + STATUS_UNCOMMITTED + ";");
    db.execSQL("CREATE VIEW " + VIEW_TEMPLATES_EXTENDED + buildViewDefinitionExtended(TABLE_TEMPLATES));
    db.execSQL(ACCOUNTS_TRIGGER_CREATE);
    insertDefaultAccount(db);
    db.execSQL(ACCOUNTTYE_METHOD_CREATE);
    insertDefaultPaymentMethods(db);
    db.execSQL(CURRENCY_CREATE);
    //category for splits needed to honour foreign constraint
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_ROWID, SPLIT_CATID);
    initialValues.put(KEY_PARENTID, SPLIT_CATID);
    initialValues.put(KEY_LABEL, "__SPLIT_TRANSACTION__");
    db.insertOrThrow(TABLE_CATEGORIES, null, initialValues);
    insertCurrencies(db);
    db.execSQL(EVENT_CACHE_CREATE);
    db.execSQL(STALE_URIS_CREATE);
    db.execSQL(STALE_URI_TRIGGER_CREATE);
    db.execSQL("CREATE INDEX transactions_cat_id_index on " + TABLE_TRANSACTIONS + "(" + KEY_CATID + ")");
    db.execSQL("CREATE INDEX templates_cat_id_index on " + TABLE_TEMPLATES + "(" + KEY_CATID + ")");
}

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

long addToOutgoing(SQLiteDatabase db, String appId, String to, String type, JSONObject json) {
    if (DBG) {//  w ww . j  a  va  2s.c  om
        Log.d(TAG, "Adding to outgoing; to: " + to + ", json: " + json);
    }
    try {
        long timestamp = new Date().getTime();
        prepareForSending(json, type, timestamp, appId);
        ContentValues cv = new ContentValues();
        cv.put(DbObject._ID, getNextId());
        cv.put(DbObject.APP_ID, appId);
        cv.put(DbObject.FEED_NAME, "friend");
        cv.put(DbObject.CONTACT_ID, Contact.MY_ID);
        cv.put(DbObject.DESTINATION, to);
        cv.put(DbObject.TYPE, type);
        cv.put(DbObject.JSON, json.toString());
        cv.put(DbObject.SEQUENCE_ID, 0);
        cv.put(DbObject.TIMESTAMP, timestamp);
        if (cv.getAsString(DbObject.JSON).length() > SIZE_LIMIT)
            throw new RuntimeException("Messasge size is too large for sending");
        return db.insertOrThrow(DbObject.TABLE, null, cv);
    } catch (Exception e) {
        // TODO, too spammy
        //e.printStackTrace(System.err);
        return -1;
    }
}

From source file:org.pixmob.freemobile.netstat.SyncServiceTesting.java

private void run(Intent intent, final SQLiteDatabase db) throws Exception {
    final long now = dateAtMidnight(System.currentTimeMillis());

    Log.i(TAG, "Initializing statistics before uploading");

    final LongSparseArray<DailyStat> stats = new LongSparseArray<>(15);
    final Set<Long> uploadedStats = new HashSet<>(15);
    final long statTimestampStart = now - 7 * DAY_IN_MILLISECONDS;

    // Get pending uploads.
    Cursor pendingUploadsCursor = null;
    try {//  ww w .  ja va2  s.  c  om
        pendingUploadsCursor = db.query("daily_stat_testing",
                new String[] { "stat_timestamp", "orange", "free_mobile", "free_mobile_3g", "free_mobile_4g",
                        "free_mobile_femtocell", "sync" },
                "stat_timestamp>=? AND stat_timestamp<?",
                new String[] { String.valueOf(statTimestampStart), String.valueOf(now) }, null, null, null);
        while (pendingUploadsCursor.moveToNext()) {
            final long d = pendingUploadsCursor.getLong(0);
            final int sync = pendingUploadsCursor.getInt(6);
            if (SYNC_UPLOADED == sync) {
                uploadedStats.add(d);
            } else if (SYNC_PENDING == sync) {
                final DailyStat s = new DailyStat();
                s.orange = pendingUploadsCursor.getInt(1);
                s.freeMobile = pendingUploadsCursor.getInt(2);
                s.freeMobile3G = pendingUploadsCursor.getInt(3);
                s.freeMobile4G = pendingUploadsCursor.getInt(4);
                s.freeMobileFemtocell = pendingUploadsCursor.getInt(5);
                stats.put(d, s);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        try {
            if (pendingUploadsCursor != null)
                pendingUploadsCursor.close();
        } catch (Exception e) {
            Log.e(TAG, Log.getStackTraceString(e));
        }
    }

    // Compute missing uploads.
    final ContentValues cv = new ContentValues();
    db.beginTransaction();
    try {
        for (long d = statTimestampStart; d < now; d += DAY_IN_MILLISECONDS) {
            if (stats.get(d) == null && !uploadedStats.contains(d)) {
                final DailyStat s = computeDailyStat(d);
                cv.put("stat_timestamp", d);
                cv.put("orange", s.orange);
                cv.put("free_mobile", s.freeMobile);
                cv.put("free_mobile_3g", s.freeMobile3G);
                cv.put("free_mobile_4g", s.freeMobile4G);
                cv.put("free_mobile_femtocell", s.freeMobileFemtocell);
                cv.put("sync", SYNC_PENDING);
                db.insertOrThrow("daily_stat_testing", null, cv);
                stats.put(d, s);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }

    // Delete old statistics.
    if (DEBUG) {
        Log.d(TAG, "Cleaning up upload database");
    }
    db.delete("daily_stat_testing", "stat_timestamp<?", new String[] { String.valueOf(statTimestampStart) });

    // Check if there are any statistics to upload.
    final int statsLen = stats.size();
    if (statsLen == 0) {
        Log.i(TAG, "Nothing to upload");
        return;
    }

    // Check if the remote server is up.
    final HttpClient client = createHttpClient();
    try {
        client.head(createServerUrl(null)).execute();
    } catch (HttpClientException e) {
        Log.w(TAG, "Remote server is not available: cannot upload statistics", e);
        return;
    }

    // Upload statistics.
    Log.i(TAG, "Uploading statistics");
    final JSONObject json = new JSONObject();
    final String deviceId = getDeviceId();
    final boolean deviceWasRegistered = intent.getBooleanExtra(EXTRA_DEVICE_REG, false);
    for (int i = 0; i < statsLen; ++i) {
        final long d = stats.keyAt(i);
        final DailyStat s = stats.get(d);

        try {
            json.put("timeOnOrange", s.orange);
            json.put("timeOnFreeMobile", s.freeMobile);
            json.put("timeOnFreeMobile3g", s.freeMobile3G);
            json.put("timeOnFreeMobile4g", s.freeMobile4G);
            json.put("timeOnFreeMobileFemtocell", s.freeMobileFemtocell);
        } catch (JSONException e) {
            final IOException ioe = new IOException("Failed to prepare statistics upload");
            ioe.initCause(e);
            throw ioe;
        }

        final String url = createServerUrl(
                "/device/" + deviceId + "/daily/" + DateFormat.format("yyyyMMdd", d));
        if (DEBUG) {
            Log.d(TAG, "Uploading statistics for " + DateUtils.formatDate(d) + " to: " + url);
        }

        final byte[] rawJson = json.toString().getBytes("UTF-8");
        try {
            client.post(url).content(rawJson, "application/json")
                    .expect(HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_NOT_FOUND)
                    .to(new HttpResponseHandler() {
                        @Override
                        public void onResponse(HttpResponse response) throws Exception {
                            final int sc = response.getStatusCode();
                            if (HttpURLConnection.HTTP_NOT_FOUND == sc) {
                                // Check if the device has just been
                                // registered.
                                if (deviceWasRegistered) {
                                    throw new IOException("Failed to upload statistics");
                                } else {
                                    // Got 404: the device does not exist.
                                    // We need to register this device.
                                    registerDevice(deviceId);

                                    // Restart this service.
                                    startService(new Intent(getApplicationContext(), SyncServiceTesting.class)
                                            .putExtra(EXTRA_DEVICE_REG, true));
                                }
                            } else if (HttpURLConnection.HTTP_OK == sc) {
                                // Update upload database.
                                cv.clear();
                                cv.put("sync", SYNC_UPLOADED);
                                db.update("daily_stat_testing", cv, "stat_timestamp=?",
                                        new String[] { String.valueOf(d) });

                                if (DEBUG) {
                                    Log.d(TAG, "Upload done for " + DateUtils.formatDate(d));
                                }
                            }
                        }
                    }).execute();
        } catch (HttpClientException e) {
            final IOException ioe = new IOException("Failed to send request with statistics");
            ioe.initCause(e);
            throw ioe;
        }
    }
}

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  .  ja v a 2s  .co 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();
        }
    }

}