Android 中什么时候关闭光标?

发布于 2024-10-01 07:23:46 字数 266 浏览 0 评论 0原文

我有一个应用程序,它使用游标通过 rawQuery 从 SQLite DB 选择数据,以填充 Android 中的 ListView。每次用户单击列表视图项时,我都会创建一个新的 Activity 实例来重新填充列表视图。

是否最好调用 cursor.close()db.close() 来避免内存问题?实际上,我的 Activity 的 OnDestroy() 中有 db.close()

I have an app that uses a cursor to select data via rawQuery from an SQLite DB to populate a ListView in Android. Every time the user clicks on a listview item I create a new instance of Activity to re-populate listview.

Is it better to call cursor.close() and db.close() to avoid memory problems? I actually have db.close() in OnDestroy() of my activity.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南汐寒笙箫 2024-10-08 07:23:46

在方法中检索到该特定对象的值后,您可以关闭光标。

顺便说一句...您不必每次都为用户点击事件重新创建 listview 。只需通知列表视图上设置的适配器数据发生了一些变化即可。

像这样的东西

youradaptername.notifyDataSetChanged();

应该会自动重新填充您的 listview 中的内容。

You can close the cursor once you have retrieved the values for that particular object inside your method.

btw...You don't have to recreate a listview every time for a user click event. Just notify that there is some change in data of your adapter that has been set on the listview.

Something like

youradaptername.notifyDataSetChanged();

This should repopulate contents inside ur listview automatically.

〃温暖了心ぐ 2024-10-08 07:23:46

好吧,如果您每次同一个 Activity 都创建一个新实例(尽管我不确定这是一个好的编程实践)。一旦完成遍历/迭代列表视图的源,您就可以关闭光标。

示例:

示例实现类似于

//Pre cursor code
startManagingCursor(cursor);
if (cursor.moveToFirst()) {
    do {
        if (cursor.getString(0).equals(value)) {
            cursor.close();
            a = true;
            return a;
        }
    } while (cursor.moveToNext());
}

//Close cursor here, when its work is complete
cursor.close();

//Post cursor code ...

Well if you are creating a new instance every time of the same Activity (though I am not sure its a good programming practice). You can close the cursor as soon as your have finished traversing / iterating through the source of the listview.

Example:

A sample implementation would be something like

//Pre cursor code
startManagingCursor(cursor);
if (cursor.moveToFirst()) {
    do {
        if (cursor.getString(0).equals(value)) {
            cursor.close();
            a = true;
            return a;
        }
    } while (cursor.moveToNext());
}

//Close cursor here, when its work is complete
cursor.close();

//Post cursor code ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文