For example consider this function
public void insertRow(CoolObject coolObject) {
ContentValues values = new ContentValues();
values.put("some field name", coolObject.getSomeValue());
//and so on and so on
mDatabase.open();
mDatabase.insertWithOnConflict("CoolTable",
null,
values,
SQLiteDatabase.CONFLICT_IGNORE);
mDatabase.close();
}
I open the database, do an SQL command of some kind using the database, then close the database again.
Now consider this:
public void insertRows(List<CoolObject> coolObjectList) {
mDatabase.beginTransaction();
try {
for (CoolObject coolObject : coolObjectList) {
insertRow(coolObject);
}
mDatabase.setTransactionSuccessful();
}
finally {
mDatabase.endTransaction();
}
}
In this case I run a loop that calls insertRow()
repeatedly, but within the framework of a single database transaction.
My question:
Is it a problem that I call open and close as I do? It may make sense for a single call, but I worry that if I am calling the insert row over and over again, that's a lot of opening and closing.
And if the database is closed by the time I finish the row operation, do I have to open it again even for the things like mDatabase.beginTransaction();
or mDatabase.setTransactionSuccessful();
or mDatabase.endTransaction();
?
I also can't just take the open and close out of the insertRow()
either and add it to the start and end of the insertRows()
method either because then it's, well, not in insertRow()
now so if I want to call that function by itself I am no longer opening/closing.
What's the accepted way to get around these errors?