Reputation: 32233
I'm making some tests and every time I call to SQLiteOpenHelper.close() and then I try to reopen the database with, for example, SQLiteOpenHelper.getWritableDatabase() I get the exception java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase
Is there some way of reopen the database? or I should re-create the SQLiteOpenHelper object?
Here goes the code, it crashes the second time the method getNoteCount is called
public DBController(Context ctx) {
this.mContext = ctx.getApplicationContext();
mDbHelper = new OpenHelper(mContext);
}
public int getNoteCount(){
SQLiteDatabase mDb =mDbHelper.getWritableDatabase();
Cursor c= mDb.query("notes", null, null, null, null, null, null);
int result=c.getCount();
c.close();
mDb.close();
return result;
}
private static class OpenHelper extends SQLiteOpenHelper {
DatabaseHelper(Context ctx) {
super(ctx, DB_NAME, null, DB_VERSION);
}
............
}
I'm considering to make something like this:
public abstract class DBHelper {
private SQLiteOpenHelper openHelper;
private int openCount = 0;
protected abstract SQLiteOpenHelper newSQLiteOpenHelper();
public void openDatabase() {
open();
}
public void closeDatabase() {
close();
}
protected synchronized SQLiteDatabase open() {
if (openHelper == null) {
openHelper = newSQLiteOpenHelper();
}
openCount++;
return openHelper.getWritableDatabase();
}
protected synchronized void close() {
openCount--;
if (openCount == 0) {
openHelper.close();
openHelper = null;
}
}
}
and use it this way
public class DBController extends DBHelper{
public DBController(Context ctx) {
this.mContext = ctx.getApplicationContext();
}
@Override
protected SQLiteOpenHelper newSQLiteOpenHelper() {
return new OpenHelper(mContext);
}
public int getNoteCount(){
SQLiteDatabase mDb =open();
Cursor c= mDb.query("notes", null, null, null, null, null, null);
int result=c.getCount();
c.close();
close();
return result;
}
}
Upvotes: 2
Views: 3184
Reputation: 3425
From what I've read, your not supposed to close the database until the application is destroyed. See Android error - close() was never explicitly called on database
Upvotes: 1