Reputation: 929
I use the SQLite DB in my Android app. I'm not 100% sure which database objects do I have to close when I'm done with reading/writing with the DB:
For example this code:
public int getLocalSavedPartsAmount() {
int partsAmount;
PartsAppDbHelper dbHelper = new PartsAppDbHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] columns = {...};
Cursor cursor = db.(...);
partsAmount = cursor.getCount();
//which one do I have to close here?
cursor.close(); //1
dbHelper.close(); //2
db.close(); //3
return partsAmount ;
}
Do I need to close 1, 2 and 3? Is it important in which order to close?
Upvotes: 1
Views: 63
Reputation: 56938
You should always close a Cursor when finished with it, a Cursor also requires that the Database is open.
You don't really need to close the database at all.
dbHelper.close closes the database(s).
When you you call getWritableDatabase or getReabableDatabase (this generally gets a writable database anyway), it opens the database and caches it, so generally the same open is used until you close it.
Opening a database can be quite intensive so you should minimise closes so you don't have to open it again.
Cusrors, each has an underlying file slot. File slots are limited, use them all and the App will crash.
So
public int getLocalSavedPartsAmount() {
int partsAmount;
PartsAppDbHelper dbHelper = new PartsAppDbHelper(context);
SQLiteDatabase db = dbHelper.getReadableDatabase();
String[] columns = {...};
Cursor cursor = db.(...);
partsAmount = cursor.getCount();
//which one do I have to close here?
cursor.close(); //1
return partsAmount ;
}
Would be sufficient.
Upvotes: 2
Reputation: 326
You need to close cursor and database connection, they are pretty important. Because these both cause memory issue to your app.
After your operation completed, you should close cursor first
if(cursor != null)
{
cursor.close();
}
And you should close database connection,
if(db.isOpen())
{
db.close();
}
Hope it will help you.
Upvotes: 0