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

The following are Jave code examples for showing how to use endTransaction() 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: RetroMusicPlayer   File: BlacklistStore.java   View Source Code Vote up 6 votes
private void addPathImpl(File file) {
    if (file == null || contains(file)) {
        return;
    }
    String path = FileUtil.safeGetCanonicalPath(file);

    final SQLiteDatabase database = getWritableDatabase();
    database.beginTransaction();

    try {
        // add the entry
        final ContentValues values = new ContentValues(1);
        values.put(BlacklistStoreColumns.PATH, path);
        database.insert(BlacklistStoreColumns.NAME, null, values);

        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
    }
}
 
Example 2
Project: Udacity_Sunshine   File: WeatherProvider.java   View Source Code Vote up 6 votes
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    final int match = sUriMatcher.match(uri);
    switch (match) {
        case WEATHER:
            db.beginTransaction();
            int returnCount = 0;
            try {
                for (ContentValues value : values) {
                    normalizeDate(value);
                    long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);
                    if (_id != -1) {
                        returnCount++;
                    }
                }
                db.setTransactionSuccessful();
            } finally {
                db.endTransaction();
            }
            getContext().getContentResolver().notifyChange(uri, null);
            return returnCount;
        default:
            return super.bulkInsert(uri, values);
    }
}
 
Example 3
Project: robird-reborn   File: RobirdContentProvider.java   View Source Code Vote up 6 votes
@Override
public int bulkInsert(Uri uri, ContentValues[] values) {
    SQLiteDatabase database = openHelper(getContext()).getWritableDatabase();
    Contract contract = findMatchingContract(uri);

    try {
        database.beginTransaction();

        for (ContentValues value : values) {
            database.insert(contract.getTable(), null, value);
        }

        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
    }

    if (values.length > 0)
        getContext().getContentResolver().notifyChange(uri, null);

    database.close();

    return values.length;
}
 
Example 4
Project: LaunchTime   File: DB.java   View Source Code Vote up 6 votes
public void setCategoryOrder(List<String> apps) {
    SQLiteDatabase db = this.getWritableDatabase();

    try {
        db.beginTransaction();

        for (int i = 0; i < apps.size(); i++) {

            ContentValues values = new ContentValues();

            values.put(INDEX, i);

            db.update(TAB_ORDER_TABLE, values, CATID + "=?", new String[]{apps.get(i)});
        }

        db.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e("LaunchDB", "Can't setCategoryOrder ", e);

    } finally {
        db.endTransaction();
    }
}
 
Example 5
Project: KomaMusic   File: FavoriteSong.java   View Source Code Vote up 6 votes
public boolean isFavorite(long songId) {
    final SQLiteDatabase database = mMusicDatabase.getWritableDatabase();
    database.beginTransaction();

    Cursor cursor = null;
    try {
        cursor = database.query(FavoriteSongColumns.NAME, new String[]{FavoriteSongColumns.SONGID},
                FavoriteSongColumns.SONGID + " =? ", new String[]{String.valueOf(songId)}, null, null, null);
        if (cursor != null && cursor.getCount() > 0) {
            return true;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
        database.setTransactionSuccessful();
        database.endTransaction();
    }
    return false;
}
 
Example 6
Project: iosched-reader   File: ScheduleProvider.java   View Source Code Vote up 6 votes
/**
 * Apply the given set of {@link ContentProviderOperation}, executing inside
 * a {@link SQLiteDatabase} transaction. All changes will be rolled back if
 * any single one fails.
 */
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        final int numOperations = operations.size();
        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
        for (int i = 0; i < numOperations; i++) {
            results[i] = operations.get(i).apply(this, results, i);
        }
        db.setTransactionSuccessful();
        return results;
    } finally {
        db.endTransaction();
    }
}
 
Example 7
Project: MKAPP   File: DatabaseHelper.java   View Source Code Vote up 6 votes
public void addForward(int protocol, int dport, String raddr, int rport, int ruid) {
    lock.writeLock().lock();
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransactionNonExclusive();
        try {
            ContentValues cv = new ContentValues();
            cv.put("protocol", protocol);
            cv.put("dport", dport);
            cv.put("raddr", raddr);
            cv.put("rport", rport);
            cv.put("ruid", ruid);

            if (db.insert("forward", null, cv) < 0)
                Log.e(TAG, "Insert forward failed");

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

    notifyForwardChanged();
}
 
Example 8
Project: financisto1-holo   File: DatabaseAdapter.java   View Source Code Vote up 6 votes
public void deleteAttribute(long id) {
       SQLiteDatabase db = db();
	db.beginTransaction();
	try {
		Attribute attr=getAttribute(id);
		String key=attr.remoteKey;
		String[] p = new String[]{String.valueOf(id)};
		db.delete(ATTRIBUTES_TABLE, AttributeColumns.ID+"=?", p);
		db.delete(CATEGORY_ATTRIBUTE_TABLE, CategoryAttributeColumns.ATTRIBUTE_ID+"=?", p);
		db.delete(TRANSACTION_ATTRIBUTE_TABLE, TransactionAttributeColumns.ATTRIBUTE_ID+"=?", p);
		db.setTransactionSuccessful();
		writeDeleteLog(ATTRIBUTES_TABLE, key);
	} finally {
		db.endTransaction();
	}
}
 
Example 9
Project: MyBP   File: DatabaseHelper.java   View Source Code Vote up 6 votes
@Override
public void onCreate(SQLiteDatabase database) {
    try {
        database.beginTransaction();

        new PlanTable().create(database);
        new IncomePlanTable().create(database);
        new ExpensesPlanTable().create(database);
        new IncomeTable().create(database);
        new ExpensesTable().create(database);

        database.setTransactionSuccessful();
    } finally {
        database.endTransaction();
    }
}
 
Example 10
Project: AsyncQuery   File: DataProvider.java   View Source Code Vote up 5 votes
private int insertInBulk(SQLiteDatabase database, String tableName, ContentValues[] values) {
    database.beginTransaction();

    for (ContentValues value : values) {
        database.insertOrThrow(tableName, null, value);
    }

    database.setTransactionSuccessful();
    database.endTransaction();
    return values.length;
}
 
Example 11
Project: financisto1-holo   File: DatabaseAdapter.java   View Source Code Vote up 5 votes
public void replaceRate(ExchangeRate rate, long originalDate) {
    SQLiteDatabase db = db();
    db.beginTransaction();
    try {
        replaceRateInTransaction(rate, originalDate, db);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
 
Example 12
Project: nifi-android-s2s   File: SQLiteDataPacketQueueTest.java   View Source Code Vote up 5 votes
@Test
public void testSizeAgeOff() throws IOException {
    int numPackets = 110000;
    List<DataPacket> dataPackets = new ArrayList<>(numPackets);
    for (int i = 0; i < numPackets; i++) {
        dataPackets.add(new ByteArrayDataPacket(Collections.singletonMap("id", "testId" + i), ("testPayload" + i).getBytes(Charsets.UTF_8)));
    }
    sqLiteDataPacketQueue.enqueue(dataPackets.iterator());
    Collections.reverse(dataPackets);

    List<DataPacket> expectedDataPackets = new ArrayList<>();
    long size = 0L;
    for (DataPacket dataPacket : dataPackets) {
        size += sqLiteDataPacketQueue.getAttributesBytes(dataPacket).length;
        size += dataPacket.getSize();
        if (size <= MAX_SIZE) {
            expectedDataPackets.add(dataPacket);
        }
    }

    SQLiteDatabase writableDatabase = siteToSiteDB.getWritableDatabase();
    writableDatabase.beginTransaction();
    try {
        sqLiteDataPacketQueue.ageOffSize(writableDatabase);
        writableDatabase.setTransactionSuccessful();
    } finally {
        writableDatabase.endTransaction();
        writableDatabase.close();
    }

    assertDataPacketsMatchIterator(expectedDataPackets);
}
 
Example 13
Project: GoUbiquitous   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 14
Project: GitHub   File: MediaVariationsIndexDatabase.java   View Source Code Vote up 5 votes
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  db.beginTransaction();
  try {
    db.execSQL(SQL_DROP_TABLE);
    db.setTransactionSuccessful();
  } finally {
    db.endTransaction();
  }
  onCreate(db);
}
 
Example 15
Project: airgram   File: DataBaseAccess.java   View Source Code Vote up 5 votes
public Long insertOrUpdateUpdate(UpdateModel update) {
    SQLiteDatabase writableDatabase = this.openHelper.getWritableDatabase();
    writableDatabase.beginTransaction();
    try {
        Long valueOf;
        ContentValues contentValues = new ContentValues();
        contentValues.put(DBConstants.UPDATE_COL_TYPE, Integer.valueOf(update.getType()));
        contentValues.put(DBConstants.UPDATE_COL_OLD_VALUE, update.getOldValue());
        contentValues.put(DBConstants.UPDATE_COL_NEW_VALUE, update.getNewValue());
        contentValues.put(DBConstants.UPDATE_COL_USER_ID, Integer.valueOf(update.getUserId()));
        contentValues.put(DBConstants.UPDATE_COL_IS_NEW, Integer.valueOf(update.isNew() ? 1 : 0));
        if (update.getChangeDate() != null) {
            contentValues.put(DBConstants.UPDATE_COL_CHANGE_DATE, update.getChangeDate());
        }
        if (update.getId() == null) {
            long result = writableDatabase.insertOrThrow(DBConstants.TABLE_UPDATE, null, contentValues);
            writableDatabase.setTransactionSuccessful();
            valueOf = Long.valueOf(result);
        } else {
            writableDatabase.update(DBConstants.TABLE_UPDATE, contentValues, "_id=" + update.getId().longValue(), null);
            writableDatabase.setTransactionSuccessful();
            valueOf = update.getId();
            writableDatabase.endTransaction();
        }
        return valueOf;
    } finally {
        writableDatabase.endTransaction();
    }
}
 
Example 16
Project: financisto1-holo   File: MainActivity.java   View Source Code Vote up 5 votes
private void initialLoad() {
    long t3, t2, t1, t0 = System.currentTimeMillis();
    DatabaseAdapter db = new DatabaseAdapter(this);
    db.open();
    try {
        SQLiteDatabase x = db.db();
        x.beginTransaction();
        t1 = System.currentTimeMillis();
        try {
            updateFieldInTable(x, DatabaseHelper.CATEGORY_TABLE, 0, "title", getString(R.string.no_category));
            updateFieldInTable(x, DatabaseHelper.CATEGORY_TABLE, -1, "title", getString(R.string.split));
            updateFieldInTable(x, DatabaseHelper.PROJECT_TABLE, 0, "title", getString(R.string.no_project));
            updateFieldInTable(x, DatabaseHelper.LOCATIONS_TABLE, 0, "name", getString(R.string.current_location));
            x.setTransactionSuccessful();
        } finally {
            x.endTransaction();
        }
        t2 = System.currentTimeMillis();
        if (MyPreferences.shouldUpdateHomeCurrency(this)) {
            db.setDefaultHomeCurrency();
        }
        CurrencyCache.initialize(db.em());
        t3 = System.currentTimeMillis();
        if (MyPreferences.shouldRebuildRunningBalance(this)) {
            db.rebuildRunningBalances();
        }
        if (MyPreferences.shouldUpdateAccountsLastTransactionDate(this)) {
            db.updateAccountsLastTransactionDate();
        }
    } finally {
        db.close();
    }
    long t4 = System.currentTimeMillis();
    Log.d("Financisto", "Load time = " + (t4 - t0) + "ms = " + (t2 - t1) + "ms+" + (t3 - t2) + "ms+" + (t4 - t3) + "ms");
}
 
Example 17
Project: SQLite-Performance   File: IntegerInsertsRawBatchTransactionCase.java   View Source Code Vote up 5 votes
@Override
public Metrics runCase() {
    mDbHelper = new DbHelper(App.getInstance(), IntegerInsertsRawBatchTransactionCase.class.getSimpleName());
    Metrics result = new Metrics(getClass().getSimpleName()+" ("+mInsertions+" insertions)", mTestSizeIndex);
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    result.started();

    db.beginTransaction();
    doInsertions(db, mInsertions);
    db.setTransactionSuccessful();
    db.endTransaction();

    result.finished();
    return result;
}
 
Example 18
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 19
Project: android-dev-challenge   File: WeatherProvider.java   View Source Code Vote up 4 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)) {
//          COMPLETED (2) Only perform our implementation of bulkInsert if the URI matches the CODE_WEATHER code
            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 != 0) {
                            rowsInserted++;
                        }
                    }
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }

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

//              COMPLETED (3) Return the number of rows inserted from our implementation of bulkInsert
                return rowsInserted;

//          COMPLETED (4) If the URI does match match CODE_WEATHER, return the super implementation of bulkInsert
            default:
                return super.bulkInsert(uri, values);
        }
    }
 
Example 20
Project: GitHub   File: DataSupport.java   View Source Code Vote up 3 votes
/**
 * Deletes the record in the database. The record must be saved already.<br>
 * The data in other tables which is referenced with the record will be
 * removed too.
 * 
 * <pre>
 * Person person;
 * ....
 * if (person.isSaved()) {
 * 		person.delete();
 * }
 * </pre>
 * 
 * @return The number of rows affected. Including cascade delete rows.
 */
public synchronized int delete() {
	SQLiteDatabase db = Connector.getDatabase();
	db.beginTransaction();
	try {
		DeleteHandler deleteHandler = new DeleteHandler(db);
		int rowsAffected = deleteHandler.onDelete(this);
		baseObjId = 0;
		db.setTransactionSuccessful();
		return rowsAffected;
	} finally {
		db.endTransaction();
	}
}