Java Code Examples for android.database.sqlite.SQLiteDatabase.setTransactionSuccessful()

The following are Jave code examples for showing how to use setTransactionSuccessful() of the android.database.sqlite.SQLiteDatabase class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: blockvote   File: StatsProvider.java   View Source Code Vote up 6 votes
@SuppressWarnings("SameParameterValue")
private void upsert(@NonNull SQLiteDatabase db, @NonNull String table, @NonNull ContentValues values, @NonNull String idCol) {
	try {
		db.beginTransaction();
		String   where = idCol + " = ?";
		String[] args  = {values.getAsString(idCol)};
		int      rows  = db.update(table, values, where, args);
		if (rows == 0) {
			long inserted = db.insert(table, null, values);
			if (inserted == -1) {
				throw new SQLException("failed to insert row into '" + table + "' - see logcat.");
			}
		}
		db.setTransactionSuccessful();
	} finally {
		db.endTransaction();
	}
}
 
Example 2
Project: Movie-Notifier-Android   File: DBHelper.java   View Source Code Vote up 6 votes
public void addCinema(Cinema cinema) {
    if(getCinemaByID(cinema.getID()) != null) {
        updateCinema(cinema);
    } else {
        SQLiteDatabase db = getWritableDatabase();
        db.beginTransaction();
        try {
            db.insertOrThrow("Cinemas", null, cinema.toContentValues());
            db.setTransactionSuccessful();
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            db.endTransaction();
        }
    }
}
 
Example 3
Project: SQLite-Performance   File: IntegerSQLiteStatementTransactionCase.java   View Source Code Vote up 6 votes
@Override
public Metrics runCase() {
    mDbHelper = new DbHelper(App.getInstance(), IntegerSQLiteStatementTransactionCase.class.getSimpleName());
    Metrics result = new Metrics(getClass().getSimpleName()+" ("+mInsertions+" insertions)", mTestSizeIndex);
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    result.started();
    SQLiteStatement stmt = db.compileStatement("INSERT INTO inserts_1 (val) VALUES (?)");
    db.beginTransaction();
    for (int i = 0; i < mInsertions; i++) {
        stmt.bindLong(1, mRandom.nextInt());
        stmt.executeInsert();
        stmt.clearBindings();
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    result.finished();
    return result;
}
 
Example 4
Project: Trivia-Knowledge   File: DemoHelperClass.java   View Source Code Vote up 6 votes
public List getBoomId() {
    String coloumns[] = {BOOM};
    SQLiteDatabase db = this.getWritableDatabase();
    db.beginTransaction();
    Cursor cursor = db.query(TABLE_NAME12, coloumns, null, null, null, null, null);
    List<Integer> list = new ArrayList<>();
    while (cursor.moveToNext()) {
        int boomValue = cursor.getInt(0);
        list.add(boomValue);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    cursor.close();
    db.close();
    return list;
}
 
Example 5
Project: android-training-2017   File: DbOperations.java   View Source Code Vote up 6 votes
@Override
public int delete(final String table, @Nullable final String selection, @Nullable final String[] selectionArgs) {
    final SQLiteDatabase database = mHelper.getWritableDatabase();
    int count = 0;

    database.beginTransaction();

    try {
        count = database.delete(table, selection, selectionArgs);

        database.setTransactionSuccessful();
    } catch (final Exception e) {
        Log.e(this.getClass().getSimpleName(), e.getLocalizedMessage());
    } finally {
        database.endTransaction();
    }

    return count;
}
 
Example 6
Project: PADC-SFC-News   File: MMNewsProvider.java   View Source Code Vote up 5 votes
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
    final SQLiteDatabase db = mDBHelper.getWritableDatabase();
    String tableName = getTableName(uri);
    int insertedCount = 0;

    try {
        db.beginTransaction();
        for (ContentValues cv : values) {
            long _id = db.insert(tableName, null, cv);
            if (_id > 0) {
                insertedCount++;
            }
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
        //db.close();
    }

    Context context = getContext();
    if (context != null) {
        context.getContentResolver().notifyChange(uri, null);
    }

    return insertedCount;
}
 
Example 7
Project: Android-SQLite-Master-Project   File: UserDao.java   View Source Code Vote up 5 votes
public static List<User> save(@NonNull SQLiteDatabase database, @NonNull List<User> users) {
    final SQLiteStatement statement = database.compileStatement(UserContract.Script.Insert.INSERT);
    try {
        database.beginTransaction();
        for (User user : users) {
            insertUser(statement, user);
        }
        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
    }
    return users;
}
 
Example 8
Project: financisto1-holo   File: DatabaseAdapter.java   View Source Code Vote up 5 votes
public void deleteTransaction(long id) {
       SQLiteDatabase db = db();
	db.beginTransaction();
	try {
           deleteTransactionNoDbTransaction(id);
		db.setTransactionSuccessful();
	} finally {
		db.endTransaction();			
	}
}
 
Example 9
Project: RoadLab-Pro   File: TagDAO.java   View Source Code Vote up 5 votes
public int delete(final TagModel data) {
    long id = data.getId();
    int count = 0;
    SQLiteDatabase db = getDatabase();
    try {
        db.beginTransaction();
        count = db.delete(DataBaseHelper.TABLE_TAGS, COLUMN_TAG_ID + " = " + id, null);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(TAG, e != null && e.getMessage() != null ? e.getMessage() : "");
    } finally {
        db.endTransaction();
    }
    return count;
}
 
Example 10
Project: RoadLab-Pro   File: RecordDetailsDAO.java   View Source Code Vote up 5 votes
public void deleteRecordDetails(final RecordDetailsModel recordDetailsModel) {
    long id = recordDetailsModel.getId();
    SQLiteDatabase db = getDatabase();
    try {
        db.beginTransaction();
        db.delete(DataBaseHelper.TABLE_RECORDS_DETAILS, COLUMN_RECORD_DETAILS_ID + " = " + id, null);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(TAG, e != null && e.getMessage() != null ? e.getMessage() : "");
    } finally {
        db.endTransaction();
    }
}
 
Example 11
Project: financisto1-holo   File: DatabaseAdapter.java   View Source Code Vote up 5 votes
/**
    * Deletes the selected transactions
    * @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();
	}
}
 
Example 12
Project: android-dev-challenge   File: WeatherProvider.java   View Source Code Vote up 5 votes
/**
 * Handles requests to insert a set of new rows. In Sunshine, we are only going to be
 * inserting multiple rows of data at a time from a weather forecast. There is no use case
 * for inserting a single row of data into our ContentProvider, and so we are only going to
 * implement bulkInsert. In a normal ContentProvider's implementation, you will probably want
 * to provide proper functionality for the insert method as well.
 *
 * @param uri    The content:// URI of the insertion request.
 * @param values An array of sets of column_name/value pairs to add to the database.
 *               This must not be {@code null}.
 *
 * @return The number of values that were inserted.
 */
@Override
public int bulkInsert(@NonNull Uri uri, @NonNull ContentValues[] values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    switch (sUriMatcher.match(uri)) {

        case CODE_WEATHER:
            db.beginTransaction();
            int rowsInserted = 0;
            try {
                for (ContentValues value : values) {
                    long weatherDate =
                            value.getAsLong(WeatherContract.WeatherEntry.COLUMN_DATE);
                    if (!SunshineDateUtils.isDateNormalized(weatherDate)) {
                        throw new IllegalArgumentException("Date must be normalized to insert");
                    }

                    long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
                    if (_id != -1) {
                        rowsInserted++;
                    }
                }
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }

            if (rowsInserted > 0) {
                getContext().getContentResolver().notifyChange(uri, null);
            }

            return rowsInserted;

        default:
            return super.bulkInsert(uri, values);
    }
}
 
Example 13
Project: financisto1-holo   File: MyEntityManager.java   View Source Code Vote up 5 votes
public void deleteProject(long id) {
       SQLiteDatabase db = db();
	db.beginTransaction();
	try {
		delete(Project.class, id);
		ContentValues values = new ContentValues();
		values.put("project_id", 0);
		db.update("transactions", values, "project_id=?", new String[]{String.valueOf(id)});
		db.setTransactionSuccessful();
	} finally {
		db.endTransaction();
	}		
}
 
Example 14
Project: SimpleUILauncher   File: RestoreDbTask.java   View Source Code Vote up 5 votes
public static boolean performRestore(DatabaseHelper helper) {
    SQLiteDatabase db = helper.getWritableDatabase();
    db.beginTransaction();
    try {
        new RestoreDbTask().sanitizeDB(helper, db);
        db.setTransactionSuccessful();
        return true;
    } catch (Exception e) {
        FileLog.e(TAG, "Failed to verify db", e);
        return false;
    } finally {
        db.endTransaction();
    }
}
 
Example 15
Project: android-training-2017   File: SqlConnector.java   View Source Code Vote up 4 votes
private void createTables(final SQLiteDatabase readableConnection, final Class<?>[] tableClassArray) {

        readableConnection.beginTransaction();

        try {
            for (final Class<?> tableClass : tableClassArray) {
                final dbTable dbTableAnnotation = tableClass.getAnnotation(dbTable.class);
                if (dbTableAnnotation != null) {
                    final String dbTableName = dbTableAnnotation.value();

                    if (TextUtils.isEmpty(dbTableName)) {
                        return;
                    }

                    final StringBuilder stringBuilder = new StringBuilder();

                    final Field[] fields = tableClass.getFields();
                    final int fieldCount = fields.length;
                    for (int i = 0; i < fieldCount; i++) {
                        final Field field = fields[i];
                        final Annotation[] fieldAnnotations = field.getAnnotations();
                        final String fieldName = (String) field.get(null);
                        String fieldType = null;

                        for (final Annotation fieldAnnotation : fieldAnnotations) {
                            final Class<?> fieldAnnotationType = fieldAnnotation.annotationType();
                            if (fieldAnnotationType.equals(dbString.class)) {
                                fieldType = ((dbString) fieldAnnotation).value();
                            } else if (fieldAnnotationType.equals(dbLong.class)) {
                                fieldType = ((dbLong) fieldAnnotation).value();
                            } else if (fieldAnnotationType.equals(dbInteger.class)) {
                                fieldType = ((dbInteger) fieldAnnotation).value();
                            }
                            if (!TextUtils.isEmpty(fieldType)) {
                                stringBuilder.append(fieldName + " " + fieldType + ",");
                            }
                        }

                    }

                    //TODO think about solution if last field marked some annotation;
                    stringBuilder.deleteCharAt(stringBuilder.length() - 1);

                    final String tableCreteQuery = String.format(TABLE_TEMPLATE, dbTableName, stringBuilder.toString());
                    readableConnection.execSQL(tableCreteQuery);
                    Log.d(TAG, "createTables() returned: " + tableCreteQuery);
                }
            }
            readableConnection.setTransactionSuccessful();
        } catch (final Exception e) {
            Log.e(TAG, "create table exception", e);
        } finally {
            readableConnection.endTransaction();
        }

    }
 
Example 16
Project: MKAPP   File: DatabaseHelper.java   View Source Code Vote up 4 votes
public void updateUsage(Usage usage, String dname) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            // There is a segmented index on uid, version, protocol, daddr and dport
            String selection = "uid = ? AND version = ? AND protocol = ? AND daddr = ? AND dport = ?";
            String[] selectionArgs = new String[]{
                    Integer.toString(usage.Uid),
                    Integer.toString(usage.Version),
                    Integer.toString(usage.Protocol),
                    dname == null ? usage.DAddr : dname,
                    Integer.toString(usage.DPort)
            };

            Cursor cursor = db.query("access", new String[]{"sent", "received", "connections"}, selection, selectionArgs, null, null, null);
            long sent = 0;
            long received = 0;
            int connections = 0;
            int colSent = cursor.getColumnIndex("sent");
            int colReceived = cursor.getColumnIndex("received");
            int colConnections = cursor.getColumnIndex("connections");
            if (cursor.moveToNext()) {
                sent = cursor.isNull(colSent) ? 0 : cursor.getLong(colSent);
                received = cursor.isNull(colReceived) ? 0 : cursor.getLong(colReceived);
                connections = cursor.isNull(colConnections) ? 0 : cursor.getInt(colConnections);
            }
            cursor.close();

            ContentValues cv = new ContentValues();
            cv.put("sent", sent + usage.Sent);
            cv.put("received", received + usage.Received);
            cv.put("connections", connections + 1);

            int rows = db.update("access", cv, selection, selectionArgs);
            if (rows != 1)
                Log.e(TAG, "Update usage failed rows=" + rows);

            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    } finally {
        lock.writeLock().unlock();
    }

    notifyAccessChanged();
}
 
Example 17
Project: BlackList   File: DatabaseAccessHelper.java   View Source Code Vote up 4 votes
public long addContact(int contactType, @NonNull String contactName, @NonNull List<ContactNumber> numbers) {
    if (numbers.size() == 0) return -1;

    long contactId = -1;
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
        // delete existing numbers from contacts
        deleteContactNumbers(numbers);

        // try to find existing contact with the same name and type
        ContactCursorWrapper cursor = getContact(contactType, contactName);
        if (cursor != null) {
            Contact contact = cursor.getContact(false);
            contactId = contact.id;
            cursor.close();
        }

        // contact was not found
        if (contactId < 0) {
            // add a new one
            contactId = addContact(contactType, contactName);
        }

        // add numbers to the contact
        if (contactId >= 0) {
            for (ContactNumber number : numbers) {
                ContentValues values = new ContentValues();
                values.put(ContactNumberTable.Column.NUMBER, number.number);
                values.put(ContactNumberTable.Column.TYPE, number.type);
                values.put(ContactNumberTable.Column.CONTACT_ID, contactId);
                if (db.insert(ContactNumberTable.NAME, null, values) < 0) {
                    return -1;
                }
            }
            db.setTransactionSuccessful();
        }
    } finally {
        db.endTransaction();
    }

    return contactId;
}
 
Example 18
Project: financisto1-holo   File: DatabaseAdapter.java   View Source Code Vote up 4 votes
/**
 * Re-populates running_balance for specific account
 * @param account selected account
 */
public void rebuildRunningBalanceForAccount(Account account) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {
        String accountId = String.valueOf(account.getId());
        db.execSQL("delete from running_balance where account_id=?", new Object[]{accountId});
        WhereFilter filter = new WhereFilter("");
        filter.put(Criteria.eq(BlotterFilter.FROM_ACCOUNT_ID, accountId));
        filter.asc("datetime");
        filter.asc("_id");
        Cursor c = getBlotterForAccountWithSplits(filter);
        Object[] values = new Object[4];
        values[0] = accountId;
        try {
            long balance = 0;
            while (c.moveToNext()) {
                long parentId = c.getLong(BlotterColumns.parent_id.ordinal());
                int isTransfer = c.getInt(BlotterColumns.is_transfer.ordinal());
                if (parentId > 0) {
                    if (isTransfer >= 0) {
                        // we only interested in the second part of the transfer-split
                        // which is marked with is_transfer=-1 (see v_blotter_for_account_with_splits)
                        continue;
                    }
                }
                long fromAccountId = c.getLong(BlotterColumns.from_account_id.ordinal());
                long toAccountId = c.getLong(BlotterColumns.to_account_id.ordinal());
                if (toAccountId > 0 && toAccountId == fromAccountId) {
                    // weird bug when a transfer is done from an account to the same account
                    continue;
                }
                balance += c.getLong(DatabaseHelper.BlotterColumns.from_amount.ordinal());
                values[1] = c.getString(DatabaseHelper.BlotterColumns._id.ordinal());
                values[2] = c.getString(DatabaseHelper.BlotterColumns.datetime.ordinal());
                values[3] = balance;
                db.execSQL("insert into running_balance(account_id,transaction_id,datetime,balance) values (?,?,?,?)", values);
            }
        } finally {
            c.close();
        }
        updateAccountLastTransactionDate(account.id);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 19
Project: ucar-weex-core   File: WXSQLiteOpenHelper.java   View Source Code Vote up 4 votes
/**
 * version 1:
 *
 *   ----------------
 *   | key | value |
 *   ---------------
 *
 * version 2:
 *
 *  ----------------------------------------
 *  | key | value | timestamp | persistent |
 *  ----------------------------------------
 **/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion != newVersion) {
        if(newVersion == 2 && oldVersion == 1){
            WXLogUtils.d(TAG_STORAGE,"storage is updating from version "+oldVersion+" to version "+newVersion);
            boolean updateResult = true;
            try {
                long start = System.currentTimeMillis();

                db.beginTransaction();
                // update table structure
                String SQL_ADD_COLUMN_TIMESTAMP = "ALTER TABLE "+TABLE_STORAGE+" ADD COLUMN "+COLUMN_TIMESTAMP+" TEXT;";
                WXLogUtils.d(TAG_STORAGE,"exec sql : "+ SQL_ADD_COLUMN_TIMESTAMP);
                db.execSQL(SQL_ADD_COLUMN_TIMESTAMP);

                String SQL_ADD_COLUMN_PERSISTENT = "ALTER TABLE "+TABLE_STORAGE+" ADD COLUMN "+COLUMN_PERSISTENT+" INTEGER;";
                WXLogUtils.d(TAG_STORAGE,"exec sql : "+ SQL_ADD_COLUMN_PERSISTENT);
                db.execSQL(SQL_ADD_COLUMN_PERSISTENT);

                // update timestamp & persistent
                String SQL_UPDATE_TABLE = "UPDATE "+TABLE_STORAGE+" SET "+ COLUMN_TIMESTAMP+" = '"+sDateFormatter.format(new Date())+"' , "+ COLUMN_PERSISTENT +" = 0";
                WXLogUtils.d(TAG_STORAGE,"exec sql : "+ SQL_UPDATE_TABLE);
                db.execSQL(SQL_UPDATE_TABLE);

                db.setTransactionSuccessful();
                long time = System.currentTimeMillis() - start;
                WXLogUtils.d(TAG_STORAGE,"storage updated success ("+time+"ms)");
            }catch (Exception e){
                WXLogUtils.d(TAG_STORAGE,"storage updated failed from version "+oldVersion+" to version "+newVersion+","+e.getMessage());
                updateResult = false;
            }finally {
                db.endTransaction();
            }
            //rollback
            if(!updateResult){
                WXLogUtils.d(TAG_STORAGE,"storage is rollback,all data will be removed");
                deleteDB();
                onCreate(db);
            }
        }else{
            deleteDB();
            onCreate(db);
        }
    }
}
 
Example 20
Project: GitHub   File: DataSupport.java   View Source Code Vote up 3 votes
/**
 * Saves the collection into database. <br>
 * 
 * <pre>
 * DataSupport.saveAll(people);
 * </pre>
 * 
 * If the model in collection is a new record gets created in the database,
 * otherwise the existing record gets updated.<br>
 * If saving process failed by any accident, the whole action will be
 * cancelled and your database will be <b>rolled back</b>. <br>
 * This method acts the same result as the below way, but <b>much more
 * efficient</b>.
 * 
 * <pre>
 * for (Person person : people) {
 * 	person.save();
 * }
 * </pre>
 * 
 * So when your collection holds huge of models,
 * {@link #saveAll(java.util.Collection)} is the better choice.
 * 
 * @param collection
 *            Holds all models to save.
 */
public static synchronized <T extends DataSupport> void saveAll(Collection<T> collection) {
	SQLiteDatabase db = Connector.getDatabase();
	db.beginTransaction();
	try {
		SaveHandler saveHandler = new SaveHandler(db);
		saveHandler.onSaveAll(collection);
		db.setTransactionSuccessful();
	} catch (Exception e) {
		throw new DataSupportException(e.getMessage(), e);
	} finally {
		db.endTransaction();
	}
}