mercredi 5 novembre 2014

Android - when to call db.setTransactionSuccessful()?


Vote count:

0




Code examples of Android SQLite transactions that I've seen appear to automatically call db.setTransactionSuccessful() right before db.endTransaction().


I am wondering if that is actually best practice or whether there should be some conditional check before calling db.setTransactionSuccessful().


In my case, I am overriding ContentProvider's bulkInsert() method and if I use a conditional check as described, my method will look like this...



@Override
public int bulkInsert(Uri uri, ContentValues[] valuesArray) {

// Open a read / write database to support the transaction.
SQLiteDatabase db = dbHelper.getWritableDatabase();

switch (uriMatcher.match(uri)) {
case BRANDS_SEARCH:

int numInserts = 0;

db.beginTransaction();

for (int i = 0; i < valuesArray.length; i++) {

// Insert the values into the table
long rowId = db.insert(BRAND_NAMES_TABLE, null, valuesArray[i]);

if (rowId > -1) {

// Increment numInserts
numInserts++;

// Construct the URI of the newly inserted row.
Uri insertedId = ContentUris.withAppendedId(CONTENT_URI_BRANDS, rowId);

// Notify any observers of the change in the data set.
getContext().getContentResolver().notifyChange(insertedId, null);

}

}

boolean allInsertAttemptsWereSuccessful = (numInserts == valuesArray.length);

if (allInsertAttemptsWereSuccessful) {
db.setTransactionSuccessful(); //todo - should this be conditional?
}
else {
//todo - ???
}

db.endTransaction();

return numInserts;

default:
//break;
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}


...is this the correct approach?


And what action should I take in the case where allInsertAttemptsWereSuccessful == false??


(I have looked in the Android docs, but very little info is provided.)



asked 1 min ago







Android - when to call db.setTransactionSuccessful()?

Aucun commentaire:

Enregistrer un commentaire