Example usage for android.database.sqlite SQLiteDatabase setTransactionSuccessful

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

Introduction

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

Prototype

public void setTransactionSuccessful() 

Source Link

Document

Marks the current transaction as successful.

Usage

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

/**
 * Changes the conflictType for the given row from the specified one to null
 * and set the sync state of this row to the indicated value. In general, you
 * should first update the local conflict record with its new values, then
 * call deleteServerConflictRowWithId(...) and then call this method.
 * //w  w w .  j  a  va 2s . c  om
 * @param db
 * @param tableId
 * @param rowId
 * @param syncState
 * @param conflictType
 */
public void restoreRowFromConflict(SQLiteDatabase db, String tableId, String rowId, SyncState syncState,
        int conflictType) {

    String whereClause = String.format("%s = ? AND %s = ?", DataTableColumns.ID,
            DataTableColumns.CONFLICT_TYPE);
    String[] whereArgs = { rowId, String.valueOf(conflictType) };

    ContentValues cv = new ContentValues();
    cv.putNull(DataTableColumns.CONFLICT_TYPE);
    cv.put(DataTableColumns.SYNC_STATE, syncState.name());
    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        db.update(tableId, cv, whereClause, whereArgs);

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

From source file:org.ttrssreader.controllers.DBHelper.java

/**
 * remove specified mark in the temporary mark table for specified
 * articles and then cleanup this table/*from w ww .  ja  v  a  2s . c  o  m*/
 *
 * @param ids  article IDs, which mark should be reseted
 * @param mark article mark to be reseted
 */
void setMarked(Map<Integer, String> ids, String mark) {
    if (!isDBAvailable())
        return;

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        ContentValues cv = new ContentValues(1);
        for (String idList : StringSupport.convertListToString(ids.keySet(), 1000)) {
            cv.putNull(mark);
            db.update(TABLE_MARK, cv, "id IN(" + idList + ")", null);
            db.delete(TABLE_MARK, "isUnread IS null AND isStarred IS null AND isPublished IS null", null);
        }

        // Insert notes afterwards and only if given note is not null
        cv = new ContentValues(1);
        for (Integer id : ids.keySet()) {
            String note = ids.get(id);
            if (note == null || note.equals(""))
                continue;

            cv.put(MARK_NOTE, note);
            db.update(TABLE_MARK, cv, "id=" + id, null);
        }

        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

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  a  2s .c o  m*/
 * @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

/**
 * Update the timestamp of the last entirely-successful synchronization
 * attempt of this table.//from  w w w  .jav a2s .c om
 * 
 * @param db
 * @param tableId
 */
public void updateDBTableLastSyncTime(SQLiteDatabase db, String tableId) {
    if (tableId == null || tableId.length() <= 0) {
        throw new IllegalArgumentException(t + ": application name and table name must be specified");
    }

    ContentValues cvTableDef = new ContentValues();
    cvTableDef.put(TableDefinitionsColumns.LAST_SYNC_TIME,
            TableConstants.nanoSecondsFromMillis(System.currentTimeMillis()));

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }
        db.update(DatabaseConstants.TABLE_DEFS_TABLE_NAME, cvTableDef, TableDefinitionsColumns.TABLE_ID + "=?",
                new String[] { tableId });
        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

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

/**
 * Deletes the server conflict row (if any) for this rowId in this tableId.
 * /*ww w .j  av  a2s .  c o m*/
 * @param db
 * @param tableId
 * @param rowId
 */
public void deleteServerConflictRowWithId(SQLiteDatabase db, String tableId, String rowId) {
    // delete the old server-values in_conflict row if it exists
    String whereClause = String.format("%s = ? AND %s = ? AND %s IN " + "( ?, ? )", DataTableColumns.ID,
            DataTableColumns.SYNC_STATE, DataTableColumns.CONFLICT_TYPE);
    String[] whereArgs = { rowId, SyncState.in_conflict.name(),
            String.valueOf(ConflictType.SERVER_DELETED_OLD_VALUES),
            String.valueOf(ConflictType.SERVER_UPDATED_UPDATED_VALUES) };

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

        db.delete(tableId, whereClause, whereArgs);

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

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

/**
 * Update the schema and data-modification ETags of a given tableId.
 * // w w w  .  ja v  a 2 s  . com
 * @param db
 * @param tableId
 * @param schemaETag
 * @param lastDataETag
 */
public void updateDBTableETags(SQLiteDatabase db, String tableId, String schemaETag, String lastDataETag) {
    if (tableId == null || tableId.length() <= 0) {
        throw new IllegalArgumentException(t + ": application name and table name must be specified");
    }

    ContentValues cvTableDef = new ContentValues();
    cvTableDef.put(TableDefinitionsColumns.SCHEMA_ETAG, schemaETag);
    cvTableDef.put(TableDefinitionsColumns.LAST_DATA_ETAG, lastDataETag);

    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }
        db.update(DatabaseConstants.TABLE_DEFS_TABLE_NAME, cvTableDef, TableDefinitionsColumns.TABLE_ID + "=?",
                new String[] { tableId });
        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
    }
}

From source file:net.smart_json_database.JSONDatabase.java

public int update(JSONEntity entity) {
    int returnValue = -1;
    if (entity.getUid() == -1) {
        return returnValue;
    }/*www.  j  a  v a 2 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:com.cyanogenmod.eleven.provider.LocalizedStore.java

/**
 * This will grab all the songs from the medistore and add the localized data to the db
 * @param selection if we only want to do this for some songs, this selection will filter it out
 *///www. j  av a 2s  .  co m
private void updateLocalizedStore(final SQLiteDatabase db, final String selection) {
    db.beginTransaction();
    try {
        Cursor cursor = null;

        try {
            final String combinedSelection = MusicUtils.MUSIC_ONLY_SELECTION
                    + (TextUtils.isEmpty(selection) ? "" : " AND " + selection);

            // order by artist/album/id to minimize artist/album re-inserts
            final String orderBy = AudioColumns.ARTIST_ID + "," + AudioColumns.ALBUM + "," + AudioColumns._ID;

            if (DEBUG) {
                Log.d(TAG, "Running selection query: " + combinedSelection);
            }

            cursor = mContext.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                    new String[] {
                            // 0
                            AudioColumns._ID,
                            // 1
                            AudioColumns.TITLE,
                            // 2
                            AudioColumns.ARTIST_ID,
                            // 3
                            AudioColumns.ARTIST,
                            // 4
                            AudioColumns.ALBUM_ID,
                            // 5
                            AudioColumns.ALBUM, },
                    combinedSelection, null, orderBy);

            long previousArtistId = -1;
            long previousAlbumId = -1;
            long artistId;
            long albumId;

            if (cursor != null && cursor.moveToFirst()) {
                do {
                    albumId = cursor.getLong(4);
                    artistId = cursor.getLong(2);

                    if (artistId != previousArtistId) {
                        previousArtistId = artistId;
                        updateArtistData(db, artistId, cursor.getString(3));
                    }

                    if (albumId != previousAlbumId) {
                        previousAlbumId = albumId;

                        updateAlbumData(db, albumId, cursor.getString(5), artistId);
                    }

                    updateSongData(db, cursor.getLong(0), cursor.getString(1), artistId, albumId);
                } while (cursor.moveToNext());
            }
        } finally {
            if (cursor != null) {
                cursor.close();
                cursor = null;
            }
        }

        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

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

/**
 * Update all rows for the given rowId to SavepointType 'INCOMPLETE' and
 * remove all but the most recent row. When used with a rowId that has
 * checkpoints, this updates to the most recent checkpoint and removes any
 * earlier checkpoints, incomplete or complete savepoints. Otherwise, it has
 * the general effect of resetting the rowId to an INCOMPLETE state.
 * /*w w w .j a v  a2 s .  c  o  m*/
 * @param db
 * @param tableId
 * @param rowId
 */
public void saveAsIncompleteMostRecentCheckpointDataInDBTableWithId(SQLiteDatabase db, String tableId,
        String rowId) {
    boolean dbWithinTransaction = db.inTransaction();
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }

        db.execSQL(
                "UPDATE \"" + tableId + "\" SET " + DataTableColumns.SAVEPOINT_TYPE + "= ? WHERE "
                        + DataTableColumns.ID + "=?",
                new String[] { SavepointTypeManipulator.incomplete(), rowId });
        db.delete(tableId,
                DataTableColumns.ID + "=? AND " + DataTableColumns.SAVEPOINT_TIMESTAMP + " NOT IN (SELECT MAX("
                        + DataTableColumns.SAVEPOINT_TIMESTAMP + ") FROM \"" + tableId + "\" WHERE "
                        + DataTableColumns.ID + "=?)",
                new String[] { rowId, rowId });

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

From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;/* w w  w.j  av  a 2  s.co m*/
    }
    final boolean force = intent.getBooleanExtra("force", false);
    try {
        Locale loc = Locale.getDefault();
        String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; T-values if present both T and B
        if (lang == null || lang.length() == 0) {
            lang = "";
        }

        int serverVersion = intent.getIntExtra("serverVersion", -1);
        boolean fromPush = serverVersion != -1;
        JSONObject versionJson = null;
        if (!fromPush) {
            versionJson = getVersion(true);
            serverVersion = versionJson.getInt("version");
        }
        int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1);
        final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, "");

        if (serverVersion <= localVersion && !force && lang.equals(localLanguage)
                && !LOCAL_DEFINITION_TESTING) {
            // don't update
            DebugLog.i("Nothing new, not updating");
            return;
        }

        // update but don't notify about it.
        boolean firstLaunchNoUpdate = ((localVersion == -1
                && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage));

        if (!firstLaunchNoUpdate) {
            DebugLog.i("There are new definitions available!");
        }

        handleAuthorMessage(versionJson, lang, intent, fromPush);

        InputStream is = getIS(URL_TICKETS_ID);
        try {
            String json = readResult(is);

            JSONObject o = new JSONObject(json);
            JSONArray array = o.getJSONArray("tickets");

            final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase();
            for (int i = 0; i < array.length(); i++) {
                final JSONObject city = array.getJSONObject(i);
                try {

                    final ContentValues cv = new ContentValues();
                    cv.put(Cities._ID, city.getInt("id"));
                    cv.put(Cities.CITY, getStringLocValue(city, lang, "city"));
                    if (city.has("city_pubtran")) {
                        cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran"));
                    }
                    cv.put(Cities.COUNTRY, city.getString("country"));
                    cv.put(Cities.CURRENCY, city.getString("currency"));
                    cv.put(Cities.DATE_FORMAT, city.getString("dateFormat"));
                    cv.put(Cities.IDENTIFICATION, city.getString("identification"));
                    cv.put(Cities.LAT, city.getDouble("lat"));
                    cv.put(Cities.LON, city.getDouble("lon"));
                    cv.put(Cities.NOTE, getStringLocValue(city, lang, "note"));
                    cv.put(Cities.NUMBER, city.getString("number"));
                    cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom"));
                    cv.put(Cities.P_DATE_TO, city.getString("pDateTo"));
                    cv.put(Cities.P_HASH, city.getString("pHash"));
                    cv.put(Cities.PRICE, city.getString("price"));
                    cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote"));
                    cv.put(Cities.REQUEST, city.getString("request"));
                    cv.put(Cities.VALIDITY, city.getInt("validity"));
                    if (city.has("confirmReq")) {
                        cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq"));
                    }
                    if (city.has("confirm")) {
                        cv.put(Cities.CONFIRM, city.getString("confirm"));
                    }

                    final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers");
                    for (int j = 0; j < additionalNumbers.length() && j < 3; j++) {
                        cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j));
                    }

                    db.beginTransaction();
                    int count = db.update(DatabaseHelper.CITY_TABLE_NAME, cv,
                            Cities._ID + " = " + cv.getAsInteger(Cities._ID), null);
                    if (count == 0) {
                        db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv);
                    }

                    db.setTransactionSuccessful();
                    getContentResolver().notifyChange(Cities.CONTENT_URI, null);
                } finally {
                    if (db.inTransaction()) {
                        db.endTransaction();
                    }
                }
            }
            Preferences.set(c, Preferences.DATA_VERSION, serverVersion);
            Preferences.set(c, Preferences.DATA_LANGUAGE, lang);
            if (!firstLaunchNoUpdate && !fromPush) {
                final int finalServerVersion = serverVersion;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(UpdateService.this,
                                getString(R.string.cities_update_completed, finalServerVersion),
                                Toast.LENGTH_LONG).show();
                    }
                });
            }
            if (LOCAL_DEFINITION_TESTING) {
                DebugLog.w(
                        "Local definition testing - data updated from assets - must be removed in production!");
            }
        } finally {
            is.close();
        }
    } catch (IOException e) {
        DebugLog.e("IOException when calling update: " + e.getMessage(), e);
    } catch (JSONException e) {
        DebugLog.e("JSONException when calling update: " + e.getMessage(), e);
    }
}