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.ichi2.libanki.Collection.java

public synchronized void close(boolean save) {
    if (mDb != null) {
        if (!mConf.optBoolean("newBury", false)) {
            boolean mod = mDb.getMod();
            mSched.unburyCards();/*from ww  w.ja  va2  s  .c o  m*/
            mDb.setMod(mod);
        }
        try {
            SQLiteDatabase db = getDb().getDatabase();
            if (save) {
                db.beginTransaction();
                try {
                    save();
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }
            } else {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
                lock();
            }
        } catch (RuntimeException e) {
            AnkiDroidApp.sendExceptionReport(e, "closeDB");
        }
        AnkiDatabaseManager.closeDatabase(mPath);
        mDb = null;
        mMedia.close();
        _closeLog();
        Timber.i("Collection closed");
    }
}

From source file:org.opendatakit.sync.ProcessRowDataChanges.java

private int processRowOutcomes(TableDefinitionEntry te, TableResource resource, TableResult tableResult,
        ArrayList<ColumnDefinition> orderedColumns, ArrayList<ColumnDefinition> fileAttachmentColumns,
        boolean hasAttachments, List<SyncRowPending> rowsToPushFileAttachments, int countSoFar,
        int totalOutcomesSize, List<SyncRow> segmentAlter, ArrayList<RowOutcome> outcomes,
        ArrayList<RowOutcome> specialCases) {

    ArrayList<SyncRowDataChanges> rowsToMoveToInConflictLocally = new ArrayList<SyncRowDataChanges>();

    // For speed, do this all within a transaction. Processing is
    // all in-memory except when we are deleting a client row. In that
    // case, there may be SDCard access to delete the attachments for
    // the client row. But that is local access, and the commit will
    // be accessing the same device.
    ////  w  w  w  . jav  a  2  s .co m
    // i.e., no network access in this code, so we can place it all within
    // a transaction and not lock up the database for very long.
    //

    SQLiteDatabase db = null;

    try {
        db = sc.getDatabase();
        db.beginTransaction();

        for (int i = 0; i < segmentAlter.size(); ++i) {
            RowOutcome r = outcomes.get(i);
            SyncRow syncRow = segmentAlter.get(i);
            if (!r.getRowId().equals(syncRow.getRowId())) {
                throw new IllegalStateException("Unexpected reordering of return");
            }
            if (r.getOutcome() == OutcomeType.SUCCESS) {

                if (r.isDeleted()) {
                    // DELETE
                    // move the local record into the 'new_row' sync state
                    // so it can be physically deleted.
                    ODKDatabaseUtils.get().updateRowETagAndSyncState(db, resource.getTableId(), r.getRowId(),
                            null, SyncState.new_row);
                    // !!Important!! update the rowETag in our copy of this row.
                    syncRow.setRowETag(r.getRowETag());
                    // and physically delete row and attachments from database.
                    ODKDatabaseUtils.get().deleteDataInExistingDBTableWithId(db, sc.getAppName(),
                            resource.getTableId(), r.getRowId());
                    tableResult.incServerDeletes();
                } else {
                    ODKDatabaseUtils.get().updateRowETagAndSyncState(db, resource.getTableId(), r.getRowId(),
                            r.getRowETag(),
                            (hasAttachments && !syncRow.getUriFragments().isEmpty())
                                    ? SyncState.synced_pending_files
                                    : SyncState.synced);
                    // !!Important!! update the rowETag in our copy of this row.
                    syncRow.setRowETag(r.getRowETag());
                    if (hasAttachments && !syncRow.getUriFragments().isEmpty()) {
                        rowsToPushFileAttachments.add(new SyncRowPending(syncRow, false, true, true));
                    }
                    // UPDATE or INSERT
                    tableResult.incServerUpserts();
                }
            } else if (r.getOutcome() == OutcomeType.FAILED) {
                if (r.getRowId() == null || !r.isDeleted()) {
                    // should never occur!!!
                    throw new IllegalStateException(
                            "Unexpected null rowId or OutcomeType.FAILED when not deleting row");
                } else {
                    // special case of a delete where server has no record of the row.
                    // server should add row and mark it as deleted.
                }
            } else if (r.getOutcome() == OutcomeType.IN_CONFLICT) {
                // another device updated this record between the time we fetched
                // changes
                // and the time we tried to update this record. Transition the record
                // locally into the conflicting state.
                // SyncState.deleted and server is not deleting
                // SyncState.new_row and record exists on server
                // SyncState.changed and new change on server
                // SyncState.in_conflict and new change on server

                // no need to worry about server in_conflict records.
                // any server in_conflict rows will be cleaned up during the
                // update of the in_conflict state.
                Integer localRowConflictType = syncRow.isDeleted() ? ConflictType.LOCAL_DELETED_OLD_VALUES
                        : ConflictType.LOCAL_UPDATED_UPDATED_VALUES;

                Integer serverRowConflictType = r.isDeleted() ? ConflictType.SERVER_DELETED_OLD_VALUES
                        : ConflictType.SERVER_UPDATED_UPDATED_VALUES;

                // figure out what the localRow conflict type sh
                SyncRow serverRow = new SyncRow(r.getRowId(), r.getRowETag(), r.isDeleted(), r.getFormId(),
                        r.getLocale(), r.getSavepointType(), r.getSavepointTimestamp(), r.getSavepointCreator(),
                        r.getFilterScope(), r.getValues(), fileAttachmentColumns);
                SyncRowDataChanges conflictRow = new SyncRowDataChanges(serverRow, syncRow, false,
                        localRowConflictType);

                rowsToMoveToInConflictLocally.add(conflictRow);
                // we transition all of these later, outside this processing loop...
            } else if (r.getOutcome() == OutcomeType.DENIED) {
                // user does not have privileges...
                specialCases.add(r);
            } else {
                // a new OutcomeType state was added!
                throw new IllegalStateException("Unexpected OutcomeType! " + r.getOutcome().name());
            }

            ++countSoFar;
            ++rowsProcessed;
            if (rowsProcessed % ROWS_BETWEEN_PROGRESS_UPDATES == 0) {
                sc.updateNotification(SyncProgressState.ROWS, R.string.altering_server_row,
                        new Object[] { resource.getTableId(), countSoFar, totalOutcomesSize },
                        10.0 + rowsProcessed * perRowIncrement, false);
            }
        }

        // process the conflict rows, if any
        conflictRowsInDb(db, resource, orderedColumns, rowsToMoveToInConflictLocally, rowsToPushFileAttachments,
                hasAttachments, tableResult);

        // and allow this to happen
        db.setTransactionSuccessful();
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
            db = null;
        }
    }

    return countSoFar;
}

From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

public void deleteTransaction(long id) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {//from w w w.java2 s . c om
        deleteTransactionNoDbTransaction(id);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

public void replaceRate(ExchangeRate rate, long originalDate) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {//from w ww . j  a va  2 s  . c o  m
        replaceRateInTransaction(rate, originalDate, db);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

public void deleteRate(long fromCurrencyId, long toCurrencyId, long date) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {/*from w w  w. j a va2 s .c  o  m*/
        deleteRateInTransaction(fromCurrencyId, toCurrencyId, date, db);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

public long insertOrUpdate(Transaction transaction, List<TransactionAttribute> attributes) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {/*ww w .  j  av a 2s .  c  o m*/
        long id = insertOrUpdateInTransaction(transaction, attributes);
        db.setTransactionSuccessful();
        return id;
    } finally {
        db.endTransaction();
    }
}

From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

/**
 * Deletes the selected transactions//from  w w  w  .ja v a2s.co m
 *
 * @param ids selected transactions' ids
 */
public void deleteSelectedTransactions(long[] ids) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {
        for (long id : ids) {
            deleteTransactionNoDbTransaction(id);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

public void saveDownloadedRates(List<ExchangeRate> downloadedRates) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {//from w ww  .jav a2  s. co  m
        for (ExchangeRate r : downloadedRates) {
            if (r.isOk()) {
                replaceRateInTransaction(r, r.date, db);
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

private void runInTransaction(String sql, long[] ids) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {//from   ww  w  .  j  av a2s.c  o  m
        int count = ids.length;
        int bucket = 100;
        int num = 1 + count / bucket;
        for (int i = 0; i < num; i++) {
            int x = bucket * i;
            int y = Math.min(count, bucket * (i + 1));
            String script = createSql(sql, ids, x, y);
            db.execSQL(script);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

public void recalculateAccountsBalances() {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {//w  w w . j  av a  2s.c  om
        Cursor accountsCursor = db.query(ACCOUNT_TABLE, new String[] { AccountColumns.ID }, null, null, null,
                null, null);
        try {
            while (accountsCursor.moveToNext()) {
                long accountId = accountsCursor.getLong(0);
                recalculateAccountBalances(accountId);
            }
        } finally {
            accountsCursor.close();
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}