This question is a follow up question to this:
When should I close a cursor and db?
I'm learning how to use SQLite for Android and I'm using this tutorial for examples:
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
I don't see any consistency as when they close the db or cursor. For example there's this method which closes the db:
public void addContact(Contact contact)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone Number
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
But right after it there's this method which does not close it:
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
Same thing for closing the cursor.
Why was it correct to close the db after adding a contact but not after getting one? Is it a good practice to always close the db after calling getWritableDatabase()
or getReadableDatabase()
? Also, if I want to add several items to the DB, is it a good practice to keep the connection to the DB open and insert many items one by one, or should I somehow insert them all togather with a single query?
I have also read that you suppose to call getWritableDatabase()
or getReadableDatabase()
with an AsyncTask
or IntentService
, but the methods in the tutorial use it serially. Which is a better practice?