Reputation: 3816
I have been learning (slowly but surely) how to do deal with sqlite databases on android systems. Using information I found here:
http://mfarhan133.wordpress.com/2010/10/24/database-crud-tutorial-for-android/
I have learned how to create, load things into and retrieve information from a database on my android system. One of the hitches was this method here:
public Cursor getClientsCursor() {
StudioTabOpenHelper dbAdapter=StudioTabOpenHelper.getDBAdapterInstance(this.getListView().getContext());
try {
dbAdapter.createDatabase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM CLIENTS;";
Cursor c = dbAdapter.selectRecordsFromDB(query, null);
//dbAdapter.close();
return c;
}
The problem was that the above code was closing the adapter I had opened...this was causing the part where I used that returned cursor to complain that database conn#0 already closed. So I commented out that dbAdapter.close(); I think this is bad in the future if i call this method again.
So my question is: Should I at the start of my application create the dbAdapter and open the database and leave it open and never close it? (how do i pass the dbAdapter around to activities, fragments etc if I go this route) ... or how can I use the getClientsCursor method as is and figure out some other way to pass back the cursor and be able to call the .close()?
/**
* Open the database
* @throws SQLException
*/
public void openDataBase() throws SQLException {
String myPath = DB_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
/**
* Close the database if exist
*/
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
My adapter code was gotten from here:
http://mfarhan133.wordpress.com/2010/10/24/database-crud-tutorial-for-android/
I just didn't call my class DBAdapter but called it StudioTabOpenHelper.
Upvotes: 0
Views: 775
Reputation: 582
You may close your adapter on the
onDestroy()
method of your activity.
Upvotes: 1