1

在扩展 SQLiteOpenHelper 的 DatabaseHelper 类中,我设置了各种方法以将 Cursors 返回到我的其他活动,这样我就不会在 DatabaseHelper 之外的任何其他类中执行任何查询。在这些方法中,我不会在之后关闭光标或数据库,而是像这样返回它:

public Cursor getCoursesLeft()
{
    // Open a readable database.
    SQLiteDatabase database = this.getReadableDatabase();

    // Query the database and return the cursor.
    return database.query(DEGREE_PLAN_TABLE, null, DEGREE_COLUMN_TAKEN + " = ?",
            new String[] { "0" }, null, null, DEGREE_COLUMN_CLASS_NAME + " COLLATE NOCASE");
}

无论从哪个 Activity 调用该方法,我都会确保关闭使用后返回的 Cursor。

由于 Cursor 是一个对象,它应该通过引用传递,对吗?所以从其他活动关闭它应该关闭原始对象,如果我理解正确关闭光标也会关闭数据库。

这是一种不好的编码习惯吗?

似乎随机地我会收到一个 LogCat 错误,说数据库上从未调用过 close,而我在代码中唯一能找到的可能是我如何在这些方法中返回游标的原因。

4

2 回答 2

1

如果我理解正确,关闭光标也会关闭数据库。

这听起来不太对劲。关闭所有游标后,您必须显式关闭数据库。logcat 错误是由于您没有关闭数据库并且可能试图打开它的另一个实例。

顺序很重要,首先是游标,然后是数据库实例。

<bad joke in 3.. 2.. 1...>

其余的听起来不像是任何不好的做法,当你需要 db 时,你只需要 db 即可。:D

[编辑]:你说你已经这样做了:

public Cursor getCoursesLeft()
{
    // Open a readable database.
    SQLiteDatabase database = this.getReadableDatabase();
                   ^^^ here you're creating a new instance of the db
which means the db is opened for reading, and the scope of this variable
is lost outside this function. This means you can not close this instance explicitly

    // Query the database and return the cursor.
    return database.query(DEGREE_PLAN_TABLE, null, DEGREE_COLUMN_TAKEN + " = ?",
            new String[] { "0" }, null, null, DEGREE_COLUMN_CLASS_NAME + " COLLATE NOCASE");
}

取而代之的是一个数据库变量,您可以在此方法之外访问它,并在您使用完光标后关闭它(并且您已经关闭了光标)

SQLiteDatabase database;
public Cursor getCoursesLeft()
{
    // Open a readable database.
    database = this.getReadableDatabase();

    // Query the database and return the cursor.
    return database.query(DEGREE_PLAN_TABLE, null, DEGREE_COLUMN_TAKEN + " = ?",
            new String[] { "0" }, null, null, DEGREE_COLUMN_CLASS_NAME + " COLLATE NOCASE");
}
public void someOtherFunction() {
  Cursor blah = getCoursesLeft();
  // do something with blah
  blah.close();
  database.close();
}
于 2013-01-01T17:26:04.023 回答
0

不关闭游标只会导致内存泄漏。关闭数据库是不同的。

关闭游标就像关闭与.file创建游标时生成的某些文件的特定连接。

因此,您应该始终关闭光标。

这是不好的编码吗?

不,是的。不要让您的 Activity 与这些临时文件混为一谈。虽然什么都不会发生,但它看起来并不好

于 2013-01-01T17:33:17.793 回答