Example usage for android.database.sqlite SQLiteDatabase beginTransaction

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

Introduction

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

Prototype

public void beginTransaction() 

Source Link

Document

Begins a transaction in EXCLUSIVE mode.

Usage

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

/** Load the expiration entries */
private void loadEntries() {
    SQLiteDatabase db = itsDbHelper.getWritableDatabase();
    try {/*from  w  w w  .j av  a2 s . c  o  m*/
        db.beginTransaction();
        loadEntries(db);
        db.setTransactionSuccessful();
    } catch (SQLException e) {
        Log.e(TAG, "Database error", e);
    } finally {
        db.endTransaction();
    }
}

From source file:com.cyanogenmod.eleven.provider.LocalizedStore.java

private void rebuildLocaleData(LocaleSet locales) {
    if (DEBUG) {//w  ww . j  av a  2s  .  co m
        Log.d(TAG, "Locale has changed, rebuilding sorting data");
    }

    final long start = SystemClock.elapsedRealtime();
    final SQLiteDatabase db = mMusicDatabase.getWritableDatabase();
    db.beginTransaction();
    try {
        db.execSQL("DELETE FROM " + SongSortColumns.TABLE_NAME);
        db.execSQL("DELETE FROM " + AlbumSortColumns.TABLE_NAME);
        db.execSQL("DELETE FROM " + ArtistSortColumns.TABLE_NAME);

        // prep the localization classes
        mLocaleSetManager.updateLocaleSet(locales);

        updateLocalizedStore(db, null);

        // Update the ICU version used to generate the locale derived data
        // so we can tell when we need to rebuild with new ICU versions.
        PropertiesStore.getInstance(mContext).storeProperty(PropertiesStore.DbProperties.ICU_VERSION,
                ICU.getIcuVersion());
        PropertiesStore.getInstance(mContext).storeProperty(PropertiesStore.DbProperties.LOCALE,
                locales.toString());

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

    if (DEBUG) {
        Log.i(TAG, "Locale change completed in " + (SystemClock.elapsedRealtime() - start) + "ms");
    }
}

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

public void saveCredentials(Credentials creds) {
    SQLiteDatabase _db = db.getWritableDatabase();
    Cursor c = null;/*  w  w  w .j  a  va2  s .  c  o m*/
    try {
        ContentValues cv = new ContentValues();
        cv.put(CredentialsDB.SCHEMA.ALIAS, creds.alias);
        cv.put(CredentialsDB.SCHEMA.URL, creds.url);
        cv.put(CredentialsDB.SCHEMA.API_KEY, creds.apiKey);
        cv.put(CredentialsDB.SCHEMA.CERT, creds.caCert);
        String[] sel = new String[] { creds.id };
        _db.beginTransaction();
        c = _db.query(CredentialsDB.SCHEMA.TABLE, idCols, credentialsDeviceIdSel, sel, null, null, null);
        if (c != null && c.getCount() > 0) {
            _db.update(CredentialsDB.SCHEMA.TABLE, cv, credentialsDeviceIdSel, sel);
        } else {
            cv.put(CredentialsDB.SCHEMA.DEVICE_ID, creds.id);
            _db.insert(CredentialsDB.SCHEMA.TABLE, null, cv);
        }
        _db.setTransactionSuccessful();
    } finally {
        _db.endTransaction();
        if (c != null)
            c.close();
    }
}

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

public void passwdFileDataChanged(PasswdFileData fileData) {
    try {//from ww  w .java2 s .  c om
        SQLiteDatabase db = itsDbHelper.getWritableDatabase();
        try {
            db.beginTransaction();
            Long id = getDbUriId(fileData.getUri(), db);
            if (id != null) {
                doUpdatePasswdFileData(id, fileData, db);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } catch (SQLException e) {
        Log.e(TAG, "Database error", e);
    }
}

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

/**
 * Clear all notifications after being confirmed
 *///from w  w  w  .j av a  2 s.  c  o m
public void handleClearAllConfirmed() {
    try {
        SQLiteDatabase db = itsDbHelper.getWritableDatabase();
        try {
            db.beginTransaction();
            db.delete(DB_TABLE_EXPIRYS, null, null);
            db.delete(DB_TABLE_URIS, null, null);
            loadEntries(db);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } catch (SQLException e) {
        Log.e(TAG, "Database error", e);
    }
}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

@SuppressWarnings("unchecked")
public void loadUnitClassifications() {
    final SQLiteDatabase db = getWritableDatabase();
    final JSONObject jo = loadInitialWeights(R.raw.unit_classification);

    db.beginTransaction();
    final ContentValues cv = new ContentValues();
    for (final Iterator i = jo.keys(); i.hasNext();) {
        final String unit = (String) i.next();
        final String description = jo.optString(unit);
        final String fprint = getFingerprint(unit);
        cv.put(ClassificationEntry._FACTOR_FPRINT, fprint);
        cv.put(ClassificationEntry._DESCRIPTION, description);
        db.insert(DB_CLASSIFICATION_TABLE, null, cv);
    }// w  ww  . j a  v  a2 s .c  o  m
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
    Log.d(TAG, "Successfully added " + jo.length() + " classification entries.");
}

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

/**
 * Set whether notifications are enabled for a password file
 *///from   w  w w .ja v  a  2 s. c  o  m
public void setPasswdExpiryNotif(@NonNull PasswdFileData fileData, boolean enabled) {
    try {
        SQLiteDatabase db = itsDbHelper.getWritableDatabase();
        try {
            db.beginTransaction();
            Long uriId = getDbUriId(fileData.getUri(), db);
            if (enabled) {
                if (uriId == null) {
                    enablePasswdExpiryNotif(fileData, db);
                }
            } else {
                if (uriId != null) {
                    removeUri(uriId, db);
                    loadEntries(db);
                }
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } catch (SQLException e) {
        Log.e(TAG, "Database error", e);
    }
}

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
 *///from  w w w  .j  a v  a  2s . c o 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.mariotaku.twidere.util.content.DatabaseUpgradeHelper.java

public static void safeUpgrade(final SQLiteDatabase db, final String table, final String[] newColNames,
        final String[] newColTypes, final boolean dropDirectly, final boolean strictMode,
        final Map<String, String> colAliases, final OnConflict onConflict) {

    if (newColNames == null || newColTypes == null || newColNames.length != newColTypes.length)
        throw new IllegalArgumentException(
                "Invalid parameters for upgrading table " + table + ", length of columns and types not match.");

    // First, create the table if not exists.
    final NewColumn[] newCols = NewColumn.createNewColumns(newColNames, newColTypes);
    final String createQuery = createTable(true, table).columns(newCols).buildSQL();
    db.execSQL(createQuery);/*from   w  ww . j av  a 2  s  . com*/

    // We need to get all data from old table.
    final String[] oldCols = getColumnNames(db, table);
    if (strictMode) {
        final String oldCreate = getCreateSQL(db, table);
        final Map<String, String> map = getTypeMapByCreateQuery(oldCreate);
        boolean different = false;
        for (final NewColumn newCol : newCols) {
            if (!newCol.getType().equalsIgnoreCase(map.get(newCol.getName()))) {
                different = true;
            }
        }
        if (!different)
            return;
    } else if (oldCols == null || TwidereArrayUtils.contentMatch(newColNames, oldCols))
        return;
    if (dropDirectly) {
        db.beginTransaction();
        db.execSQL(dropTable(true, table).getSQL());
        db.execSQL(createQuery);
        db.setTransactionSuccessful();
        db.endTransaction();
        return;
    }
    final String tempTable = String.format(Locale.US, "temp_%s_%d", table, System.currentTimeMillis());
    db.beginTransaction();
    db.execSQL(alterTable(table).renameTo(tempTable).buildSQL());
    db.execSQL(createQuery);
    final String[] notNullCols = getNotNullColumns(newCols);
    final String insertQuery = createInsertDataQuery(table, tempTable, newColNames, oldCols, colAliases,
            notNullCols, onConflict);
    if (insertQuery != null) {
        db.execSQL(insertQuery);
    }
    db.execSQL(dropTable(true, tempTable).getSQL());
    db.setTransactionSuccessful();
    db.endTransaction();
}

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

private void mergeDbs() {
    Log.d(LOG_TAG, "update received - juggling dbs");
    // Get main database, attach temp db to it.
    SQLiteDatabase mainDb = dataService.getHelper().getWritableDatabase();
    mainDb.execSQL("attach database ? as ka_temp",
            new Object[] { dataService.getDatabasePath("ka_temp").getAbsolutePath() });

    mainDb.beginTransaction();
    try {/*from   w  ww  .  j  a  v  a 2s  . com*/

        // Maintain download status.
        String sql = "select max(download_status), dlm_id, youtube_id from video where download_status != ? group by youtube_id";
        Cursor c = mainDb.rawQuery(sql, new String[] { "" + Video.DL_STATUS_NOT_STARTED });
        Cursor c1;
        String[] videoIds = new String[c.getCount()];
        int i = 0;
        while (c.moveToNext()) {
            String youtube_id = c.getString(c.getColumnIndex("youtube_id"));
            String download_status = c.getString(c.getColumnIndex("max(download_status)"));
            long dlm_id = c.getLong(c.getColumnIndex("dlm_id"));
            videoIds[i++] = youtube_id;
            ContentValues v = new ContentValues();
            v.put("download_status", download_status);
            v.put("dlm_id", dlm_id);
            String[] idArg = new String[] { youtube_id };
            mainDb.update("ka_temp.video", v, "youtube_id = ?", idArg);

            // cursor over parent topics of this video
            sql = "select ka_temp.topic._id from ka_temp.topic, ka_temp.topicvideo, ka_temp.video where ka_temp.video.youtube_id=? and ka_temp.topicvideo.video_id=ka_temp.video.readable_id and ka_temp.topicvideo.topic_id=ka_temp.topic._id";
            c1 = mainDb.rawQuery(sql, idArg);
            Log.d(LOG_TAG, String.format("updating counts for %d topics", c1.getCount()));
            while (c1.moveToNext()) {
                String topicId = c1.getString(c1.getColumnIndex("_id"));
                DatabaseHelper.incrementDownloadedVideoCounts(mainDb, topicId, "ka_temp.topic");
            }
            c1.close();
        }
        c.close();

        mainDb.execSQL("delete from topic");
        mainDb.execSQL("insert into topic select * from ka_temp.topic");

        mainDb.execSQL("delete from topicvideo");
        mainDb.execSQL("insert into topicvideo select * from ka_temp.topicvideo");

        mainDb.execSQL("delete from video");
        mainDb.execSQL("insert into video select * from ka_temp.video");

        mainDb.setTransactionSuccessful();
    } finally {
        mainDb.endTransaction();
        mainDb.execSQL("detach database ka_temp");
    }

    Log.d(LOG_TAG, "finished juggling");
}