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

The following are Jave code examples for showing how to use beginTransaction() 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: PeSanKita-android   File: MessagingDatabase.java   View Source Code Vote up 6 votes
protected <D extends Document<I>, I> void removeFromDocument(long messageId, String column, I object, Class<D> clazz) throws IOException {
  SQLiteDatabase database = databaseHelper.getWritableDatabase();
  database.beginTransaction();

  try {
    D           document = getDocument(database, messageId, column, clazz);
    Iterator<I> iterator = document.getList().iterator();

    while (iterator.hasNext()) {
      I item = iterator.next();

      if (item.equals(object)) {
        iterator.remove();
        break;
      }
    }

    setDocument(database, messageId, column, document);
    database.setTransactionSuccessful();
  } finally {
    database.endTransaction();
  }
}
 
Example 2
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 3
Project: KomaMusic   File: FavoriteSong.java   View Source Code Vote up 6 votes
public int removeFavoriteSong(final long[] songId) {
    final SQLiteDatabase database = mMusicDatabase.getWritableDatabase();
    database.beginTransaction();

    Cursor cursor = null;
    int deleted = 0;
    try {
        for (long aSongId : songId) {
            cursor = database.query(FavoriteSongColumns.NAME, new String[]{FavoriteSongColumns.SONGID},
                    FavoriteSongColumns.SONGID + " =? ", new String[]{String.valueOf(aSongId)}, null, null, null);
            if (cursor != null && cursor.getCount() >= 0) {
                database.delete(FavoriteSongColumns.NAME, FavoriteSongColumns.SONGID + " =? ",
                        new String[]{String.valueOf(aSongId)});
                deleted++;
            }
        }
        return deleted;
    } finally {
        if (cursor != null) {
            cursor.close();
        }
        database.setTransactionSuccessful();
        database.endTransaction();
    }
}
 
Example 4
Project: SQLite-Performance   File: IntegerInsertsTransactionCase.java   View Source Code Vote up 6 votes
@Override
public Metrics runCase() {
    mDbHelper = new DbHelper(App.getInstance(), IntegerInsertsTransactionCase.class.getSimpleName());
    Metrics result = new Metrics(getClass().getSimpleName()+" ("+mInsertions+" insertions)", mTestSizeIndex);
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    result.started();
    db.beginTransaction();
    ContentValues values = new ContentValues(1);
    for (int i = 0; i < mInsertions; i++) {
        values.put("val", mRandom.nextInt());
        db.insert("inserts_1", null, values);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    result.finished();
    return result;
}
 
Example 5
Project: Trivia-Knowledge   File: DemoHelperClass.java   View Source Code Vote up 6 votes
public List<Integer> GetQid() {
    String coloumns[] = {CORRECTNO};
    SQLiteDatabase db = this.getWritableDatabase();

    db.beginTransaction();
    Cursor cursor = db.query(TABLE_NAME2, coloumns, null, null, null, null, null);
    List<Integer> list = new ArrayList<>();

    while (cursor.moveToNext()) {
        int questionId = cursor.getInt(0);
        list.add(questionId);
    }

    db.setTransactionSuccessful();
    db.endTransaction();
    cursor.close();
    db.close();
    return list;
}
 
Example 6
Project: stynico   File: SQLManager.java   View Source Code Vote up 6 votes
@Override
public void transactionAround(boolean readOnly, CallBack callback)
{
	SQLiteDatabase sqLiteDatabase = null;
	if (readOnly)
	{
		sqLiteDatabase = this.getReadableDatabase();
	}
	else
	{
		sqLiteDatabase = this.getWritableDatabase();
	}
	sqLiteDatabase.beginTransaction();
	callback.doSomething(sqLiteDatabase);
	sqLiteDatabase.setTransactionSuccessful();
	sqLiteDatabase.endTransaction();
}
 
Example 7
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 8
Project: SQLite-Performance   File: BatchedSQLiteStatementTestCase.java   View Source Code Vote up 6 votes
@Override
public Metrics runCase() {
    mDbHelper = new DbHelper(App.getInstance(), getClass().getName());
    Metrics result = new Metrics(getClass().getSimpleName()+" ("+mInsertions+" insertions)", mTestSizeIndex);
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    byte[] titleByteArry = new byte[50];
    byte[] urlByteArray = new byte[100];
    byte[] lyricsByteArray = new byte[2000];
    byte[] aboutByteArray = new byte[2000];
    Map<Integer, SQLiteStatement> statementCache = new HashMap<>();

    result.started();
    db.beginTransaction();
    mInsertId = 1;
    doInsertions(db, mInsertions, statementCache, titleByteArry, urlByteArray, lyricsByteArray, aboutByteArray);
    db.setTransactionSuccessful();
    db.endTransaction();
    result.finished();

    return result;
}
 
Example 9
Project: aos-MediaLib   File: MusicProvider.java   View Source Code Vote up 6 votes
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
        throws OperationApplicationException {
    if (DBG) Log.d(TAG, "applyBatch");
    ContentProviderResult[] result = null;
    SQLiteDatabase db = mDbHolder.get();
    db.beginTransaction();
    try {
         result = super.applyBatch(operations);
         db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
    if (result != null) {
        mCr.notifyChange(MusicStore.ALL_CONTENT_URI, null);
    }
    return result;
}
 
Example 10
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 11
Project: Quiz-Game   File: TriviaQuizHelper.java   View Source Code Vote up 5 votes
List<TriviaQuestion> getAllOfTheQuestions() {

        List<TriviaQuestion> questionsList = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        String coloumn[] = {UID, QUESTION, OPTA, OPTB, OPTC, OPTD, ANSWER};
        Cursor cursor = db.query(TABLE_NAME, coloumn, null, null, null, null, null);


        while (cursor.moveToNext()) {
            TriviaQuestion question = new TriviaQuestion();
            question.setId(cursor.getInt(0));
            question.setQuestion(cursor.getString(1));
            question.setOptA(cursor.getString(2));
            question.setOptB(cursor.getString(3));
            question.setOptC(cursor.getString(4));
            question.setOptD(cursor.getString(5));
            question.setAnswer(cursor.getString(6));
            questionsList.add(question);
        }

        db.setTransactionSuccessful();
        db.endTransaction();
        cursor.close();
        db.close();
        return questionsList;
    }
 
Example 12
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 13
Project: MyFlightbookAndroid   File: CustomPropertyTypesSvc.java   View Source Code Vote up 5 votes
private void updateCache(CustomPropertyType[] rgcpt) {
    // note that these calls will close the db, so we do them first.
    DBCache dbc = new DBCache();
    dbc.flushCache(TABLENAME, true);
    Boolean fResult = false;

    // now, we get an open db
    SQLiteDatabase db = MFBMain.mDBHelper.getWritableDatabase();

    try {
        // I've read that multiple inserts are much faster inside a
        // transaction.
        db.beginTransaction();
        try {
            for (CustomPropertyType cpt : rgcpt) {
                ContentValues cv = new ContentValues();
                cpt.ToContentValues(cv);

                long l = db.insertOrThrow(TABLENAME, null, cv);
                if (l < 0)
                    throw new Error("Error inserting CustomPropertyType");
            }
            db.setTransactionSuccessful();
            fResult = true;
        } catch (Exception ex) {
            this.setLastError(ex.getMessage());
        } finally {
            db.endTransaction();
        }
    } catch (Exception e) {
        this.setLastError(e.getMessage());
    }

    if (fResult)
        dbc.updateCache(TABLENAME);
}
 
Example 14
Project: SimpleUILauncher   File: LauncherProvider.java   View Source Code Vote up 5 votes
/**
 * Deletes any empty folder from the DB.
 * @return Ids of deleted folders.
 */
private ArrayList<Long> deleteEmptyFolders() {
    ArrayList<Long> folderIds = new ArrayList<>();
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        // Select folders whose id do not match any container value.
        String selection = LauncherSettings.Favorites.ITEM_TYPE + " = "
                + LauncherSettings.Favorites.ITEM_TYPE_FOLDER + " AND "
                + LauncherSettings.Favorites._ID +  " NOT IN (SELECT " +
                        LauncherSettings.Favorites.CONTAINER + " FROM "
                            + Favorites.TABLE_NAME + ")";
        Cursor c = db.query(Favorites.TABLE_NAME,
                new String[] {LauncherSettings.Favorites._ID},
                selection, null, null, null, null);
        while (c.moveToNext()) {
            folderIds.add(c.getLong(0));
        }
        c.close();
        if (!folderIds.isEmpty()) {
            db.delete(Favorites.TABLE_NAME, Utilities.createDbSelectionQuery(
                    LauncherSettings.Favorites._ID, folderIds), null);
        }
        db.setTransactionSuccessful();
    } catch (SQLException ex) {
        Log.e(TAG, ex.getMessage(), ex);
        folderIds.clear();
    } finally {
        db.endTransaction();
    }
    return folderIds;
}
 
Example 15
Project: pvdisplay   File: PvDataOperations.java   View Source Code Vote up 5 votes
public void saveDaily(List<DailyPvDatum> dailyPvData) {
    SQLiteDatabase db = pvDataHelper.getWritableDatabase();

    db.beginTransaction();
    String sql = "REPLACE INTO " + PvDataContract.DailyPvData.TABLE_NAME +
            "(" + PvDataContract.DailyPvData.COLUMN_NAME_YEAR +
            "," + PvDataContract.DailyPvData.COLUMN_NAME_MONTH +
            "," + PvDataContract.DailyPvData.COLUMN_NAME_DAY +
            "," + PvDataContract.DailyPvData.COLUMN_NAME_ENERGY_GENERATED +
            "," + PvDataContract.DailyPvData.COLUMN_NAME_PEAK_POWER +
            "," + PvDataContract.DailyPvData.COLUMN_NAME_CONDITION +
            ") VALUES (?,?,?,?,?,?);";
    SQLiteStatement statement = db.compileStatement(sql);
    double maxEnergyGenerated = Double.MIN_VALUE;
    for (DailyPvDatum dailyPvDatum : dailyPvData) {
        statement.clearBindings();
        statement.bindLong(1, dailyPvDatum.getYear());
        statement.bindLong(2, dailyPvDatum.getMonth());
        statement.bindLong(3, dailyPvDatum.getDay());
        statement.bindDouble(4, dailyPvDatum.getEnergyGenerated());
        statement.bindDouble(5, dailyPvDatum.getPeakPower());
        statement.bindString(6, dailyPvDatum.getCondition());
        statement.execute();
        maxEnergyGenerated = Math.max(maxEnergyGenerated, dailyPvDatum.getEnergyGenerated());
    }
    db.setTransactionSuccessful();
    db.endTransaction();

    db.close();
    Log.d(TAG, "Saved " + dailyPvData.size() + " rows of daily PV data to database");

    RecordPvDatum recordPvDatum = loadRecord();
    if (maxEnergyGenerated > recordPvDatum.getDailyEnergyGenerated()) {
        recordPvDatum.setDailyEnergyGenerated(maxEnergyGenerated);
        saveRecord(recordPvDatum);
    }
}
 
Example 16
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 17
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 18
Project: RoadLab-Pro   File: GeoTagDAO.java   View Source Code Vote up 5 votes
public void deleteItemsWithMeasurementId(final long measurementId) {
    SQLiteDatabase db = getDatabase();
    try {
        db.beginTransaction();
        db.delete(DataBaseHelper.TABLE_GEO_TAGS, COLUMN_GEO_TAG_MEASUREMENT_ID + " = " + measurementId, null);
        db.setTransactionSuccessful();
    } catch (Exception e) {
        Log.e(TAG, e != null && e.getMessage() != null ? e.getMessage() : "");
    } finally {
        db.endTransaction();
    }
}
 
Example 19
Project: Trivia-Knowledge   File: DemoHelperClass.java   View Source Code Vote up 5 votes
public List<Questions> getAllOfTheQuestions() {

        List<Questions> questionsList = new ArrayList<>();
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        String coloumn[] = {UID, QUESTION, ANSWER, ANSWER2, RANDOMANS1, RANDOMANS2, USELESSSTRING};
        Cursor cursor = db.query(TABLE_NAME, coloumn, null, null, null, null, null);


        while (cursor.moveToNext()) {
            Questions question = new Questions();
            question.setID(cursor.getInt(0));
            question.setQuestion(cursor.getString(1));
            question.setAnswer(cursor.getString(2));
            question.setAnswer2(cursor.getString(3));
            question.setRANDOMANS1(cursor.getString(4));
            question.setRANDOMANS2(cursor.getString(5));
            question.setUSELESSSTRING(cursor.getString(6));
            questionsList.add(question);
        }

        db.setTransactionSuccessful();
        db.endTransaction();
        cursor.close();
        db.close();
        return questionsList;
    }
 
Example 20
Project: FlickLauncher   File: LauncherProvider.java   View Source Code Vote up 4 votes
/**
 * Recreates workspace table and migrates data to the new table.
 */
public boolean recreateWorkspaceTable(SQLiteDatabase db) {
    db.beginTransaction();
    try {
        Cursor c = db.query(WorkspaceScreens.TABLE_NAME,
                new String[] {LauncherSettings.WorkspaceScreens._ID},
                null, null, null, null,
                LauncherSettings.WorkspaceScreens.SCREEN_RANK);
        ArrayList<Long> sortedIDs = new ArrayList<Long>();
        long maxId = 0;
        try {
            while (c.moveToNext()) {
                Long id = c.getLong(0);
                if (!sortedIDs.contains(id)) {
                    sortedIDs.add(id);
                    maxId = Math.max(maxId, id);
                }
            }
        } finally {
            c.close();
        }

        db.execSQL("DROP TABLE IF EXISTS " + WorkspaceScreens.TABLE_NAME);
        addWorkspacesTable(db, false);

        // Add all screen ids back
        int total = sortedIDs.size();
        for (int i = 0; i < total; i++) {
            ContentValues values = new ContentValues();
            values.put(LauncherSettings.WorkspaceScreens._ID, sortedIDs.get(i));
            values.put(LauncherSettings.WorkspaceScreens.SCREEN_RANK, i);
            addModifiedTime(values);
            db.insertOrThrow(WorkspaceScreens.TABLE_NAME, null, values);
        }
        db.setTransactionSuccessful();
        mMaxScreenId = maxId;
    } catch (SQLException ex) {
        // Old version remains, which means we wipe old data
        Log.e(TAG, ex.getMessage(), ex);
        return false;
    } finally {
        db.endTransaction();
    }
    return true;
}