SQLiteOpenHelper和close方法

时间:2013-05-17 18:13:13

标签: java android sql sqlite

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

1 个答案:

答案 0 :(得分:1)

从我读过的内容来看,在应用程序被销毁之前,你不应该关闭数据库。见Android error - close() was never explicitly called on database