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:syncthing.android.settings.AppSettings.java

public void removeCredentials(Credentials creds) {
    SQLiteDatabase _db = db.getWritableDatabase();
    Cursor c = null;/*  w  w w.j  a va  2 s.com*/
    try {
        _db.beginTransaction();
        _db.delete(CredentialsDB.SCHEMA.TABLE, credentialsDeviceIdSel, new String[] { creds.id });
        c = _db.query(CredentialsDB.SCHEMA.TABLE, idCols, credentialsDefaultSel, null, null, null, null);
        if (c != null && c.getCount() == 0) {
            c.close();
            //no default set a new one
            c = _db.query(CredentialsDB.SCHEMA.TABLE, idCols, null, null, null, null, null);
            if (c != null && c.moveToFirst()) {
                ContentValues cv = new ContentValues();
                cv.put(CredentialsDB.SCHEMA.DEFAULT, 1);
                _db.update(CredentialsDB.SCHEMA.TABLE, cv, idSel, new String[] { c.getString(0) });
            }
        }
        _db.setTransactionSuccessful();
    } finally {
        _db.endTransaction();
        if (c != null)
            c.close();
    }
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

/**
 * This method removes the entry from the content provider, and also removes
 * any associated files. files: form.xml, [formmd5].formdef, formname
 * {directory}//from   w w w .  j a  v  a 2s  .  c  o m
 */
@Override
public int delete(Uri uri, String where, String[] whereArgs) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() < 1 || segments.size() > 2) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of segments!) " + uri);
    }

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    String uriFormId = ((segments.size() == 2) ? segments.get(1) : null);
    boolean isNumericId = StringUtils.isNumeric(uriFormId);

    // Modify the where clause to account for the presence of
    // a form id. Accept either:
    // (1) numeric _ID value
    // (2) string FORM_ID value.
    String whereId;
    String[] whereIdArgs;

    if (uriFormId == null) {
        whereId = where;
        whereIdArgs = whereArgs;
    } else {
        if (TextUtils.isEmpty(where)) {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=?";
            whereIdArgs = new String[1];
            whereIdArgs[0] = uriFormId;
        } else {
            whereId = (isNumericId ? FormsColumns._ID : FormsColumns.FORM_ID) + "=? AND (" + where + ")";
            whereIdArgs = new String[whereArgs.length + 1];
            whereIdArgs[0] = uriFormId;
            for (int i = 0; i < whereArgs.length; ++i) {
                whereIdArgs[i + 1] = whereArgs[i];
            }
        }
    }

    Cursor del = null;
    Integer idValue = null;
    String tableIdValue = null;
    String formIdValue = null;
    HashMap<File, DirType> mediaDirs = new HashMap<File, DirType>();
    try {
        del = this.query(uri, null, whereId, whereIdArgs, null);
        if (del == null) {
            throw new SQLException("FAILED Delete into " + uri + " -- unable to query for existing records");
        }
        del.moveToPosition(-1);
        while (del.moveToNext()) {
            idValue = ODKDatabaseUtils.get().getIndexAsType(del, Integer.class,
                    del.getColumnIndex(FormsColumns._ID));
            tableIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.TABLE_ID));
            formIdValue = ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.FORM_ID));
            File mediaDir = ODKFileUtils.asAppFile(appName, ODKDatabaseUtils.get().getIndexAsString(del,
                    del.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)));
            mediaDirs.put(mediaDir, (tableIdValue == null) ? DirType.FRAMEWORK : DirType.FORMS);
        }
    } catch (Exception e) {
        log.w(t, "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Delete from " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (del != null && !del.isClosed()) {
            del.close();
        }
    }

    SQLiteDatabase db = null;
    int count;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        count = db.delete(DatabaseConstants.FORMS_TABLE_NAME, whereId, whereIdArgs);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        e.printStackTrace();
        log.w(t, "Unable to perform deletion " + e.toString());
        return 0;
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    // and attempt to move these directories to the stale forms location
    // so that they do not immediately get rescanned...

    for (HashMap.Entry<File, DirType> entry : mediaDirs.entrySet()) {
        try {
            moveDirectory(appName, entry.getValue(), entry.getKey());
        } catch (IOException e) {
            e.printStackTrace();
            log.e(t, "Unable to move directory " + e.toString());
        }
    }

    if (count == 1) {
        Uri formUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName), formIdValue);
        getContext().getContentResolver().notifyChange(formUri, null);
        Uri idUri = Uri.withAppendedPath(
                Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                Long.toString(idValue));
        getContext().getContentResolver().notifyChange(idUri, null);
    } else {
        getContext().getContentResolver().notifyChange(uri, null);
    }
    return count;
}

From source file:com.cloudmine.api.db.RequestDBOpenHelper.java

/**
 * Load all of the unsynced requests, and set their status to in progress.
 * @return//from w  w  w  . jav a2s .  c o m
 */
private Cursor loadRequestTableContentsForUpdating() {
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
        String[] unsychronizedSelectionArgs = { UNSYCHRONIZED.toString() };
        Cursor cursor = db.query(BOTH_DATABASE_TABLE_JOIN, RESULTS_COLUMNS, SYNCHRONIZED_VALUE_WHERE,
                unsychronizedSelectionArgs, null, null, requestColumn(KEY_REQUEST_ID));
        cursor.getCount(); //For some reason, accessing the cursor count before performing the update is required for the load to work. Doesn't make much sense unless it is ignoring order.
        ContentValues updatedValues = getUpdateSynchronizedContentValues(IN_PROGRESS);
        db.update(REQUEST_DATABASE_TABLE, updatedValues, SYNCHRONIZED_VALUE_WHERE, unsychronizedSelectionArgs);

        db.setTransactionSuccessful();

        return cursor;
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        db.endTransaction();
    }
}

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

public void saveCredentials(Credentials creds) {
    SQLiteDatabase _db = db.getWritableDatabase();
    Cursor c = null;/*from   www.jav  a2  s.  co 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.osfans.trime.DictionaryHelper.java

private boolean importSchema(InputStream is) {
    boolean success = false;
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();/*from   ww w.j  a  v  a  2  s  .co m*/
    try {
        Yaml yaml = new Yaml();
        Map<String, Object> y = (Map<String, Object>) (yaml.load(is));
        Map<String, Object> m = (Map<String, Object>) y.get("schema");
        String schema_id = (String) m.get("schema_id");
        String name = (String) m.get("name");
        String full = yaml.dump(y);
        is.close();

        ContentValues initialValues = new ContentValues();
        initialValues.put("schema_id", schema_id);
        initialValues.put("name", name);
        initialValues.put("full", full);

        long r = db.update("schema", initialValues, "schema_id = ?", new String[] { schema_id });
        if (r == 0)
            r = db.insert("schema", null, initialValues);
        db.setTransactionSuccessful();
        success = true;
    } catch (Exception e) {
        throw new RuntimeException("Error import schema", e);
    } finally {
        db.endTransaction();
    }
    return success;
}

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

/**
 * Set whether notifications are enabled for a password file
 *///from  ww  w.  j av  a  2s .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.ericsender.android_nanodegree.popmovie.com.ericsender.android_nanodegree.popmovie.data.TestProvider.java

public void testBasicFavoriteQueries() {
    //first insert movies:
    Map<Long, ContentValues> listContentValues = TestUtilities.createSortedMovieValues(getContext(), "popular");
    Map<Long, Long> locationRowIds = TestUtilities.insertMovieRow(mContext, listContentValues);

    // Insert random favorites
    SQLiteDatabase db = new MovieDbHelper(getContext()).getWritableDatabase();
    Set<Long> insertedMoviedIds = new HashSet<>();
    try {/*w w  w.j av  a 2s .c om*/
        db.beginTransaction();
        while (insertedMoviedIds.isEmpty())
            for (Map.Entry<Long, ContentValues> e : listContentValues.entrySet())
                insertedMoviedIds.add(TestUtilities.generateRandomFavoritesAndInsert(db, e.getValue()));
        insertedMoviedIds.remove(null);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        db.close();
    }

    // Test the basic content provider query
    Cursor favCursor = mContext.getContentResolver().query(MovieContract.FavoriteEntry.CONTENT_URI, null, null,
            null, null);

    // Make sure we get the correct cursor out of the database
    TestUtilities.validateFavoritesCursor(favCursor, listContentValues, insertedMoviedIds);

    // Has the NotificationUri been set correctly? --- we can only test this easily against API
    // level 19 or greater because getNotificationUri was added in API level 19.
    if (Build.VERSION.SDK_INT >= 19) {
        assertEquals("Error: Favoriate Query did not properly set NotificationUri",
                favCursor.getNotificationUri(), MovieContract.FavoriteEntry.buildUri());
    }
}

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

public void deleteAttribute(long id) {
    SQLiteDatabase db = db();
    db.beginTransaction();//from   w  w w .j av  a  2  s.  com
    try {
        Attribute attr = get(Attribute.class, id);
        String key = attr.remoteKey;
        String[] p = new String[] { String.valueOf(id) };
        db.delete(ATTRIBUTES_TABLE, DatabaseHelper.AttributeColumns.ID + "=?", p);
        db.delete(CATEGORY_ATTRIBUTE_TABLE, DatabaseHelper.CategoryAttributeColumns.ATTRIBUTE_ID + "=?", p);
        db.delete(TRANSACTION_ATTRIBUTE_TABLE, DatabaseHelper.TransactionAttributeColumns.ATTRIBUTE_ID + "=?",
                p);
        db.setTransactionSuccessful();
        writeDeleteLog(ATTRIBUTES_TABLE, key);
    } finally {
        db.endTransaction();
    }
}

From source file:org.kontalk.provider.UsersProvider.java

private boolean setTransactionSuccessful(SQLiteDatabase db) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
        db.setTransactionSuccessful();
    return true;//www .  j a v  a  2 s  .  c om
}

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();/*w  ww . ja  v a2s .  c  o  m*/
    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);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
    Log.d(TAG, "Successfully added " + jo.length() + " classification entries.");
}