SQLite游标如何工作?

时间:2017-02-09 22:17:15

标签: android sqlite simplecursoradapter

我有以下代码:

public Cursor getListText(String [] cols) {
    Cursor cursor = null;

    if(cols != null && cols.length > 0) {
        openDb(false);
        cursor = db.query(true, Contract.Text.TABLE_NAME, cols, null, null, null
                , null, null, null);

        if(!cursor.moveToFirst()) {
            cursor = null;
        }
        closeDb();
    }

    return cursor;
}

getListText(String [] cols)返回SimpleCursorAdapter返回的光标,以显示ListView

如果我不调用cursor.moveToFirst() Android会抛出异常:

java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.

为什么会发生这种情况?只有关闭数据库closeDb();才会发生这种情况

如果有必要,我附上SimpleCursorAdapter实施:

private void listViewSetup() {
    this.listView = (ListView) findViewById(R.id.texts);
    CursorAdapterDto cursorAdapterDto = this.presenter.getListTextNames();
    Cursor cursor = cursorAdapterDto.getCursor();
    Log.v("Cursor Object", DatabaseUtils.dumpCursorToString(cursor));
    String [] contractNames = cursorAdapterDto.getContractNames();
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.custom_list_item, cursor,
            new String [] {"title"}, new int[] {R.id.itemTextView} , 2);

    listView.setAdapter(adapter);

    if(cursor == null) {
        Toast.makeText(this, "No hay textos",
                Toast.LENGTH_LONG).show();
    }
}

感谢您的帮助!

EDITED 抱歉!我想我没有解释这个问题!我知道在关闭数据库之前我必须管理游标。我想知道的是SimpleCursorAdapter如何使用光标。我的意思是如果我移动到第一个光标并关闭数据库SimpleCursorAdapter绘制listView项目! 但是如果我不移动到第一个并关闭数据库,为什么我无法访问这些项目?为什么游标内容不可用?

3 个答案:

答案 0 :(得分:1)

关闭数据库时,它会释放Cursor。在完成Cursor之前,请不要关闭数据库。如果您在活动或片段中使用Cursor,通常可以在活动/片段生命周期结束时关闭它,通常在onDestroy()onStop()

除了关于释放Cursor的问题之外,您还应该为该Activity / Fragment中的所有数据库操作使用相同的数据库连接,而不是为每个数据库操作创建/关闭连接。考虑实现database singleton以这种方式处理连接的创建。

答案 1 :(得分:0)

Erik,关闭数据库必须始终是最后一次操作。你不能在关闭数据库之后使用Cursor ,如果你确实抛出异常。

换句话说,如果数据库关闭,你就无法进入数据库并尝试读取行(这是光标的功能)......

您可以在此链接中看到更详细的说明。 (Android: Cannot perform this operation because the connection pool has been closed

我希望它有所帮助。

答案 2 :(得分:0)

您可能需要在程序中自己致电moveCursorToFirst()。这here可能会对您有所帮助。我认为通过不自己调用moveCursorToFirst(),在if()中检查它,然后数据库正在关闭,这导致错误。