【问题标题】:How SQLite cursor works?SQLite 游标是如何工作的?
【发布时间】:2017-06-28 03:00:25
【问题描述】:

我有以下代码:

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();
    }
}

感谢您的帮助!

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

【问题讨论】:

    标签: android sqlite simplecursoradapter


    【解决方案1】:

    Erik,关闭数据库必须始终是最后一个操作。 在关闭数据库后,您不能使用光标,否则会引发异常。

    换句话说,如果数据库关闭,您不能进入数据库并尝试读取行(这是游标的功能)...

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

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      当您关闭数据库时,它会释放光标。在完成光标之前不要关闭数据库。如果您在 Activity 或 Fragment 中使用 Cursor,通常可以在 Activity/Fragment 生命周期结束时将其关闭,通常在 onDestroy() 或 onStop() 中。

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

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 2012-05-09
          • 2010-10-02
          • 2015-03-22
          • 1970-01-01
          • 1970-01-01
          • 2012-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多