2

我正在做一些测试,每次我调用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;
    }
}
4

1 回答 1

1

根据我的阅读,在应用程序被销毁之前,您不应该关闭数据库。请参阅Android 错误 - close() 从未在数据库上显式调用

于 2013-06-07T16:42:02.403 回答