我正在做一些测试,每次我调用SQLiteOpenHelper.close()然后我尝试使用例如SQLiteOpenHelper.getWritableDatabase()重新打开数据库时都会出现异常java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase
有什么方法可以重新打开数据库吗?或者我应该重新创建 SQLiteOpenHelper 对象?
这是代码,它在第二次调用 getNoteCount 方法时崩溃
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);
}
............
}
我正在考虑做这样的事情:
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;
}
}
}
并以这种方式使用它
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;
}
}