Example usage for android.database.sqlite SQLiteDatabase inTransaction

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

Introduction

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

Prototype

public boolean inTransaction() 

Source Link

Document

Returns true if the current thread has a transaction pending.

Usage

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

@Override
protected void onHandleIntent(Intent intent) {
    if (intent == null) {
        return;//from  w  w  w  .j  av  a  2s .  c  o  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);
    }
}

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

/**
 * Call this when the schema on the server has changed w.r.t. the schema on
 * the device. In this case, we do not know whether the rows on the device
 * match those on the server.//from  ww w  .  j  av a  2s  .  c om
 *
 * <ul>
 * <li>Reset all 'in_conflict' rows to their original local state (changed or
 * deleted).</li>
 * <li>Leave all 'deleted' rows in 'deleted' state.</li>
 * <li>Leave all 'changed' rows in 'changed' state.</li>
 * <li>Reset all 'synced' rows to 'new_row' to ensure they are sync'd to the
 * server.</li>
 * <li>Reset all 'synced_pending_files' rows to 'new_row' to ensure they are
 * sync'd to the server.</li>
 * </ul>
 * 
 * @param db
 * @param tableId
 */
public void changeDataRowsToNewRowState(SQLiteDatabase db, String tableId) {

    StringBuilder b = new StringBuilder();

    // remove server conflicting rows
    b.setLength(0);
    b.append("DELETE FROM \"").append(tableId).append("\" WHERE ").append(DataTableColumns.SYNC_STATE)
            .append(" =? AND ").append(DataTableColumns.CONFLICT_TYPE).append(" IN (?, ?)");

    String sqlConflictingServer = b.toString();
    //@formatter:off
    String argsConflictingServer[] = { SyncState.in_conflict.name(),
            Integer.toString(ConflictType.SERVER_DELETED_OLD_VALUES),
            Integer.toString(ConflictType.SERVER_UPDATED_UPDATED_VALUES) };
    //@formatter:on

    // update local delete conflicts to deletes
    b.setLength(0);
    //@formatter:off
    b.append("UPDATE \"").append(tableId).append("\" SET ").append(DataTableColumns.SYNC_STATE).append(" =?, ")
            .append(DataTableColumns.CONFLICT_TYPE).append(" = null WHERE ")
            .append(DataTableColumns.CONFLICT_TYPE).append(" = ?");
    //@formatter:on

    String sqlConflictingLocalDeleting = b.toString();
    //@formatter:off
    String argsConflictingLocalDeleting[] = { SyncState.deleted.name(),
            Integer.toString(ConflictType.LOCAL_DELETED_OLD_VALUES) };
    //@formatter:on

    // update local update conflicts to updates
    String sqlConflictingLocalUpdating = sqlConflictingLocalDeleting;
    //@formatter:off
    String argsConflictingLocalUpdating[] = { SyncState.changed.name(),
            Integer.toString(ConflictType.LOCAL_UPDATED_UPDATED_VALUES) };
    //@formatter:on

    // reset all 'rest' rows to 'insert'
    b.setLength(0);
    //@formatter:off
    b.append("UPDATE \"").append(tableId).append("\" SET ").append(DataTableColumns.SYNC_STATE)
            .append(" =? WHERE ").append(DataTableColumns.SYNC_STATE).append(" =?");
    //@formatter:on

    String sqlRest = b.toString();
    //@formatter:off
    String argsRest[] = { SyncState.new_row.name(), SyncState.synced.name() };
    //@formatter:on

    String sqlRestPendingFiles = sqlRest;
    //@formatter:off
    String argsRestPendingFiles[] = { SyncState.new_row.name(), SyncState.synced_pending_files.name() };
    //@formatter:on

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

        db.execSQL(sqlConflictingServer, argsConflictingServer);
        db.execSQL(sqlConflictingLocalDeleting, argsConflictingLocalDeleting);
        db.execSQL(sqlConflictingLocalUpdating, argsConflictingLocalUpdating);
        db.execSQL(sqlRest, argsRest);
        db.execSQL(sqlRestPendingFiles, argsRestPendingFiles);

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

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

private void upsertDataIntoExistingDBTable(SQLiteDatabase db, String tableId,
        ArrayList<ColumnDefinition> orderedColumns, ContentValues cvValues, boolean shouldUpdate) {
    String rowId = null;/*from ww  w .  j  a  v a2s. c om*/
    String whereClause = null;
    boolean specifiesConflictType = cvValues.containsKey(DataTableColumns.CONFLICT_TYPE);
    boolean nullConflictType = specifiesConflictType && (cvValues.get(DataTableColumns.CONFLICT_TYPE) == null);
    String[] whereArgs = new String[specifiesConflictType ? (1 + (nullConflictType ? 0 : 1)) : 1];
    boolean update = false;

    if (cvValues.size() <= 0) {
        throw new IllegalArgumentException(t + ": No values to add into table " + tableId);
    }

    ContentValues cvDataTableVal = new ContentValues();
    cvDataTableVal.putAll(cvValues);

    if (cvDataTableVal.containsKey(DataTableColumns.ID)) {
        // The user specified a row id; we need to determine whether to
        // insert or update the record, or to reject the action because
        // there are either checkpoint records for this row id, or, if
        // a server conflict is associated with this row, that the
        // _conflict_type to update was not specified.
        //
        // i.e., the tuple (_id, _conflict_type) should be unique. If
        // we find that there are more than 0 or 1 records matching this
        // tuple, then we should reject the update request.
        //
        // TODO: perhaps we want to allow updates to the local conflict
        // row if there are no checkpoints on it? I.e., change the
        // tri-state conflict type to a pair of states (local / remote).
        // and all local changes are flagged local. Remote only exists
        // if the server is in conflict.

        rowId = cvDataTableVal.getAsString(DataTableColumns.ID);
        if (rowId == null) {
            throw new IllegalArgumentException(DataTableColumns.ID + ", if specified, cannot be null");
        }

        if (specifiesConflictType) {
            if (nullConflictType) {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE
                        + " IS NULL";
                whereArgs[0] = rowId;
            } else {
                whereClause = DataTableColumns.ID + " = ?" + " AND " + DataTableColumns.CONFLICT_TYPE + " = ?";
                whereArgs[0] = rowId;
                whereArgs[1] = cvValues.getAsString(DataTableColumns.CONFLICT_TYPE);
            }
        } else {
            whereClause = DataTableColumns.ID + " = ?";
            whereArgs[0] = rowId;
        }

        String sel = "SELECT * FROM " + tableId + " WHERE " + whereClause;
        String[] selArgs = whereArgs;
        Cursor cursor = rawQuery(db, sel, selArgs);

        // There must be only one row in the db for the update to work
        if (shouldUpdate) {
            if (cursor.getCount() == 1) {
                update = true;
            } else if (cursor.getCount() > 1) {
                throw new IllegalArgumentException(
                        t + ": row id " + rowId + " has more than 1 row in table " + tableId);
            }
        } else {
            if (cursor.getCount() > 0) {
                throw new IllegalArgumentException(
                        t + ": id " + rowId + " is already present in table " + tableId);
            }
        }

    } else {
        rowId = "uuid:" + UUID.randomUUID().toString();
    }

    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields
    // TODO: This is broken w.r.t. updates of partial fields

    if (!cvDataTableVal.containsKey(DataTableColumns.ID)) {
        cvDataTableVal.put(DataTableColumns.ID, rowId);
    }

    if (update) {
        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.changed.name());
        }

        if (cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                && (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                && (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    } else {

        if (!cvDataTableVal.containsKey(DataTableColumns.ROW_ETAG)
                || cvDataTableVal.get(DataTableColumns.ROW_ETAG) == null) {
            cvDataTableVal.put(DataTableColumns.ROW_ETAG, DataTableColumns.DEFAULT_ROW_ETAG);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SYNC_STATE)
                || (cvDataTableVal.get(DataTableColumns.SYNC_STATE) == null)) {
            cvDataTableVal.put(DataTableColumns.SYNC_STATE, SyncState.new_row.name());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.CONFLICT_TYPE)) {
            cvDataTableVal.putNull(DataTableColumns.CONFLICT_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_TYPE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_TYPE, DataTableColumns.DEFAULT_FILTER_TYPE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FILTER_VALUE)
                || (cvDataTableVal.get(DataTableColumns.FILTER_VALUE) == null)) {
            cvDataTableVal.put(DataTableColumns.FILTER_VALUE, DataTableColumns.DEFAULT_FILTER_VALUE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.FORM_ID)) {
            cvDataTableVal.putNull(DataTableColumns.FORM_ID);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.LOCALE)
                || (cvDataTableVal.get(DataTableColumns.LOCALE) == null)) {
            cvDataTableVal.put(DataTableColumns.LOCALE, DataTableColumns.DEFAULT_LOCALE);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TYPE)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_TYPE) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TYPE, SavepointTypeManipulator.complete());
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_TIMESTAMP)
                || cvDataTableVal.get(DataTableColumns.SAVEPOINT_TIMESTAMP) == null) {
            String timeStamp = TableConstants.nanoSecondsFromMillis(System.currentTimeMillis());
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_TIMESTAMP, timeStamp);
        }

        if (!cvDataTableVal.containsKey(DataTableColumns.SAVEPOINT_CREATOR)
                || (cvDataTableVal.get(DataTableColumns.SAVEPOINT_CREATOR) == null)) {
            cvDataTableVal.put(DataTableColumns.SAVEPOINT_CREATOR, DataTableColumns.DEFAULT_SAVEPOINT_CREATOR);
        }
    }

    cleanUpValuesMap(orderedColumns, cvDataTableVal);

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

        if (update) {
            db.update(tableId, cvDataTableVal, whereClause, whereArgs);
        } else {
            db.insertOrThrow(tableId, null, cvDataTableVal);
        }

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

}