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.ttrssreader.controllers.DBHelper.java

void markUnsynchronizedStates(Collection<Integer> ids, String mark, int state) {
    if (!isDBAvailable())
        return;//from  w  w  w  .  j a v a2s. co  m

    SQLiteDatabase db = getOpenHelper().getWritableDatabase();
    writeLock(true);
    db.beginTransaction();
    try {
        for (Integer id : ids) {
            // First update, then insert. If row exists it gets updated and second call ignores it, else the second
            // call inserts it.
            db.execSQL(String.format("UPDATE %s SET %s=%s WHERE id=%s", TABLE_MARK, mark, state, id));
            db.execSQL(String.format("INSERT OR IGNORE INTO %s (id, %s) VALUES (%s, %s)", TABLE_MARK, mark, id,
                    state));
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        writeLock(false);
    }
}

From source file:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname//from w ww .j  a v  a  2s.  c  o m
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase(Locale.getDefault()).startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

From source file:com.digicorp.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname/* w w  w . ja  v  a2s.c o m*/
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase().startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else if (jsonparams[i].isNull(j)) {
                        myStatement.bindNull(j + 1);
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

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

public long[] storeMissedSchedules(List<RestoredTransaction> restored, long now) {
    SQLiteDatabase db = db();
    db.beginTransaction();/*from  w ww .  j  a va2s  .  c  o m*/
    try {
        int count = restored.size();
        long[] restoredIds = new long[count];
        HashMap<Long, Transaction> transactions = new HashMap<Long, Transaction>();
        for (int i = 0; i < count; i++) {
            RestoredTransaction rt = restored.get(i);
            long transactionId = rt.transactionId;
            Transaction t = transactions.get(transactionId);
            if (t == null) {
                t = getTransaction(transactionId);
                transactions.put(transactionId, t);
            }
            t.id = -1;
            t.dateTime = rt.dateTime.getTime();
            t.status = TransactionStatus.RS;
            t.isTemplate = 0;
            restoredIds[i] = insertOrUpdate(t);
            t.id = transactionId;
        }
        for (Transaction t : transactions.values()) {
            db.execSQL(UPDATE_LAST_RECURRENCE, new Object[] { now, t.id });
        }
        db.setTransactionSuccessful();
        return restoredIds;
    } finally {
        db.endTransaction();
    }
}

From source file:net.smart_json_database.JSONDatabase.java

public int insert(JSONEntity entity) {

    int returnValue = -1;
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {/*from ww  w  .  j a  v  a  2  s  .  co  m*/
        db.beginTransaction();
        ContentValues values = new ContentValues();
        values.put("createDate", Util.DateToString(entity.getCreationDate()));
        values.put("updateDate", Util.DateToString(entity.getUpdateDate()));
        values.put("data", entity.getData().toString());
        values.put("type", entity.getType());
        int uid = Util.LongToInt(db.insert(TABLE_JSON_DATA, null, values));
        returnValue = uid;
        //entity.setUid(uid);
        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, uid, db) == -1) {
                throw new Exception("could not relate entity with tags");
            }
        }

        for (HasMany hasMany : entity.getHasManyRelations().values()) {
            //               for(Integer id : hasMany.getToRemove())
            //               {
            //                  deleteRelation(hasMany.getName(), uid, id, db);
            //               }

            for (Integer id : hasMany.getToAdd()) {
                insertRelation(hasMany.getName(), uid, id, db);
            }
        }

        for (BelongsTo belongsTo : entity.getBelongsToRelations().values()) {
            //               for(Integer id : belongsTo.getToRemove())
            //               {
            //                  deleteRelation(belongsTo.getName(), id ,uid,  db);
            //               }

            for (Integer id : belongsTo.getToAdd()) {
                insertRelation(belongsTo.getName(), id, uid, db);
            }
        }

        db.setTransactionSuccessful();
        notifyListenersOnEntityChange(returnValue, IDatabaseChangeListener.CHANGETYPE_INSERT);
    } catch (Exception e) {
        returnValue = -1;
    } finally {
        db.endTransaction();
        db.close();
    }
    return returnValue;
}

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

/**
 * If the tableId is not recorded in the TableDefinition metadata table, then
 * create the tableId with the indicated columns. This will synthesize
 * reasonable metadata KVS entries for table.
 * /*from   w  ww  .ja  v a  2  s  . com*/
 * If the tableId is present, then this is a no-op.
 * 
 * @param db
 * @param appName
 * @param tableId
 * @param columns
 * @return the ArrayList<ColumnDefinition> of the user columns in the table.
 */
public ArrayList<ColumnDefinition> createOrOpenDBTableWithColumns(SQLiteDatabase db, String appName,
        String tableId, List<Column> columns) {
    boolean dbWithinTransaction = db.inTransaction();
    boolean success = false;
    ArrayList<ColumnDefinition> orderedDefs = ColumnDefinition.buildColumnDefinitions(appName, tableId,
            columns);
    try {
        if (!dbWithinTransaction) {
            db.beginTransaction();
        }
        if (!hasTableId(db, tableId)) {
            createDBTableWithColumns(db, appName, tableId, orderedDefs);
        }

        if (!dbWithinTransaction) {
            db.setTransactionSuccessful();
        }
        success = true;
        return orderedDefs;
    } finally {
        if (!dbWithinTransaction) {
            db.endTransaction();
        }
        if (success == false) {

            // Get the names of the columns
            StringBuilder colNames = new StringBuilder();
            if (columns != null) {
                for (Column column : columns) {
                    colNames.append(" ").append(column.getElementKey()).append(",");
                }
                if (colNames != null && colNames.length() > 0) {
                    colNames.deleteCharAt(colNames.length() - 1);
                    WebLogger.getLogger(appName).e(t,
                            "createOrOpenDBTableWithColumns: Error while adding table " + tableId
                                    + " with columns:" + colNames.toString());
                }
            } else {
                WebLogger.getLogger(appName).e(t, "createOrOpenDBTableWithColumns: Error while adding table "
                        + tableId + " with columns: null");
            }
        }
    }
}

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

/**
 * Delete the specified rowId in this tableId. Deletion respects sync
 * semantics. If the row is in the SyncState.new_row state, then the row and
 * its associated file attachments are immediately deleted. Otherwise, the row
 * is placed into the SyncState.deleted state and will be retained until the
 * device can delete the record on the server.
 * <p>//from  ww  w  .  j  a v  a2 s .com
 * If you need to immediately delete a record that would otherwise sync to the
 * server, call updateRowETagAndSyncState(...) to set the row to
 * SyncState.new_row, and then call this method and it will be immediately
 * deleted (in this case, unless the record on the server was already deleted,
 * it will remain and not be deleted during any subsequent synchronizations).
 * 
 * @param db
 * @param appName
 * @param tableId
 * @param rowId
 */
public void deleteDataInExistingDBTableWithId(SQLiteDatabase db, String appName, String tableId, String rowId) {
    SyncState syncState = getSyncState(db, appName, tableId, rowId);

    boolean dbWithinTransaction = db.inTransaction();
    if (syncState == SyncState.new_row) {
        String[] whereArgs = { rowId };
        String whereClause = DataTableColumns.ID + " = ?";

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

            db.delete(tableId, whereClause, whereArgs);

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

        File instanceFolder = new File(ODKFileUtils.getInstanceFolder(appName, tableId, rowId));
        try {
            FileUtils.deleteDirectory(instanceFolder);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            WebLogger.getLogger(appName).e(t,
                    "Unable to delete this directory: " + instanceFolder.getAbsolutePath());
            WebLogger.getLogger(appName).printStackTrace(e);
        }
    } else if (syncState == SyncState.synced || syncState == SyncState.changed) {
        String[] whereArgs = { rowId };
        ContentValues values = new ContentValues();
        values.put(DataTableColumns.SYNC_STATE, SyncState.deleted.name());
        values.put(DataTableColumns.SAVEPOINT_TIMESTAMP,
                TableConstants.nanoSecondsFromMillis(System.currentTimeMillis()));
        try {
            if (!dbWithinTransaction) {
                db.beginTransaction();
            }

            db.update(tableId, values, DataTableColumns.ID + " = ?", whereArgs);

            if (!dbWithinTransaction) {
                db.setTransactionSuccessful();
            }
        } finally {
            if (!dbWithinTransaction) {
                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();//from   ww w  .  j  a v  a  2 s.c o m
    try {

        // 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");
}

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

/**
 * Change the conflictType for the given row from null (not in conflict) to
 * the specified one.//  w  w w  . jav  a  2 s  . c om
 * 
 * @param db
 * @param tableId
 * @param rowId
 * @param conflictType
 *          expected to be one of ConflictType.LOCAL_DELETED_OLD_VALUES (0) or
 *          ConflictType.LOCAL_UPDATED_UPDATED_VALUES (1)
 */
public void placeRowIntoConflict(SQLiteDatabase db, String tableId, String rowId, int conflictType) {

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

    ContentValues cv = new ContentValues();
    cv.put(DataTableColumns.SYNC_STATE, SyncState.in_conflict.name());
    cv.put(DataTableColumns.CONFLICT_TYPE, conflictType);

    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:info.staticfree.android.units.UnitUsageDBHelper.java

public void loadInitialUnitUsage() {
    final SQLiteDatabase db = getWritableDatabase();
    // load the initial table in
    final ContentValues cv = new ContentValues();

    Log.d(TAG, "init all weights hash");
    final HashMap<String, Integer> allUnitWeights = new HashMap<String, Integer>(Unit.table.keySet().size());
    Log.d(TAG, "adding all known weights...");
    for (final String unitName : Unit.table.keySet()) {
        // don't add all uppercase names
        if (!unitName.toUpperCase().equals(unitName)) {
            allUnitWeights.put(unitName, 0);
        }// www  .j a va  2 s . c o m
    }
    Log.d(TAG, "adding all known functions...");
    for (final String functionName : BuiltInFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    //      for (final String functionName: TabularFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    //      for (final String functionName: ComputedFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    for (final String functionName : DefinedFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    Log.d(TAG, "adding common weights");
    addAll(loadInitialWeights(R.raw.common_weights), allUnitWeights);
    Log.d(TAG, "adding regional weights");
    addAll(loadInitialWeights(R.raw.regional_weights), allUnitWeights);

    // This is so that things of common weight end up in non-random order
    // without having to do an SQL order-by.
    final ArrayList<String> sortedUnits = new ArrayList<String>(allUnitWeights.keySet());
    Log.d(TAG, "Sorting units...");
    Collections.sort(sortedUnits);
    Log.d(TAG, "Adding all sorted units...");

    final HashMap<String, String> fingerprints = loadFingerprints();

    db.beginTransaction();
    for (final String unitName : sortedUnits) {
        cv.put(UsageEntry._UNIT, unitName);
        cv.put(UsageEntry._USE_COUNT, allUnitWeights.get(unitName));

        final String fpr = fingerprints.containsKey(unitName) ? fingerprints.get(unitName)
                : getFingerprint(unitName);

        fingerprints.put(unitName, fpr);
        cv.put(UsageEntry._FACTOR_FPRINT, fpr);
        db.insert(DB_USAGE_TABLE, null, cv);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();

    context.getContentResolver().notifyChange(UsageEntry.CONTENT_URI, null);

    // If we have the right permissons, save the fingerprints file to a JSON file
    // which can then be imported into the app to speed up initial fingerpint loading.
    if (context.checkCallingOrSelfPermission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        final File externalStorage = Environment.getExternalStorageDirectory();
        final File fprintsOutput = new File(externalStorage, "units_fingerprints.json");
        final JSONObject jo = new JSONObject(fingerprints);
        try {
            final FileWriter fw = new FileWriter(fprintsOutput);
            fw.write(jo.toString(1));
            fw.close();
            Log.i(TAG, "fingerprints written to: " + fprintsOutput.getCanonicalPath());

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    Log.d(TAG, "done!");
}