尝试重新打开已关闭的对象:sqlitequery

问题描述 投票:0回答:3

所以本质上我查询数据库两次。我不明白这个错误真正来自哪里,因为我没有在任何地方关闭数据库。返回错误的代码是这样运行的。我查了一下,刚刚看到一个像我这样的案例。

BeaconHandler pullAllDB = new BeaconHandler(this);
    try {
        List<Beacon> beaconsShown = pullAllDB.getAllBeacons();
        for (final Beacon bn : beaconsShown) {
            try {
                int messageCount = pullAllDB.getMessageCount();
                Log.d("Message", messageCount + " Messages Found");
                if (messageCount > 0) {
                    //Do Something
                } else {
                    // Do Nothing
                }
            } 
            catch (Exception e) {
                e.getStackTrace();
                Log.e("Message", e.getMessage());
            }
        }
    }

以及执行查询的代码...

public int getBeaconsCount() {

    String countQuery = "SELECT * FROM " + TABLE_BASIC_BEACON;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();

}

public int getMessageCount() {

    String mcountQuery = "SELECT * FROM " + MESSAGE_BEACON;
    SQLiteDatabase mdb = this.getReadableDatabase();
    Cursor mcursor = mdb.rawQuery(mcountQuery, null);
    mcursor.close();

    // return count
    return mcursor.getCount();

}
android sqliteopenhelper sqlite
3个回答
22
投票

如果出现错误,您应该发布 logcat。它有助于查看哪一行导致了您的问题。

来自 Android 文档。

关闭()

关闭光标,释放其所有资源并使得 完全无效。

关闭后调用

mcursor.getCount()
可能会导致错误

也许可以尝试这样的事情。

int count = mcursor.getCount();
mcursor.close();

// return count
return count ;

1
投票

我在这里假设

pullAllDB
是您的数据库对象,其中包含执行查询的代码。在这种情况下,在
List<Beacon> beaconsShown = pullAllDB.getAllBeacons();
行之前,您应该执行类似
pullAllDB.open();
的操作,并在运行完查询后执行
pullAllDB.close();

总而言之,你的函数看起来像..

try {
    //open the database class here
    pullAllDB.open();

    List<Beacon> beaconsShown = pullAllDB.getAllBeacons();
    for (final Beacon bn : beaconsShown) {
        try {
            int messageCount = pullAllDB.getMessageCount();
            Log.d("Message", messageCount + " Messages Found");
            if (messageCount > 0) {
                //Do Something
            } else {
                // Do Nothing
            }
        } 
        catch (Exception e) {
            e.getStackTrace();
            Log.e("Message", e.getMessage());
        }

    //close the database here
    pullAllDB.close();
    }
}

0
投票

出现此错误的另一种情况。 如果您的片段或活动包含带有数据库游标适配器的ListView,您应该在onCreate(或onCreateView)方法中打开游标并在onDestroy方法中关闭它。我在 onStart 和 onStop 方法中执行了此操作,当 ListView 从第一行向下滚动时,当 ListView 在其 onSaveInstanceState 方法中查询光标时,遇到此错误。 onSaveInstanceState 在 onStop 之后调用,这是错误的原因。因此,仅在 Destroy 回调中关闭光标可能是安全的。

© www.soinside.com 2019 - 2024. All rights reserved.