gpt4 book ai didi

java - Android:如何关闭从类返回到 Activity 的游标

转载 作者:行者123 更新时间:2023-12-01 15:20:47 24 4
gpt4 key购买 nike

我有:Accounts.java

public class Accounts{

private SQLiteDatabase dbConfig;

public Cursor list(Context context, String db, String where, String order) {

DBHelper dbHelper = new DBHelper(context, db);
dbConfig = dbHelper.getReadableDatabase();

Cursor c = dbConfig.query("accounts", new String[]{ "iId","sName"}, where, null, null, null, order);
return c;
}
}

和:MainActivity.java

Accounts account = new Accounts();
Cursor cursor = account.list(getApplicationContext(), globalDB, null, null);
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
String name = cursor.getString(1);
}
cursor.close();

运行我的应用程序时,我收到一些 logcat 消息,例如:

close() was never explicitly called on database...

最好的预防方法是什么?如何关闭从其他类返回的游标?谢谢

最佳答案

account.list() 退出后,底层数据库连接仍然打开,但没有剩余的引用。所以,它已经泄露了。

您可以在使用完数据库后将其关闭,也可以通过使用单个全局数据库连接在应用程序的整个生命周期中保持其打开状态,该连接打开一次,在所有 Activity 中共享,并且永不关闭。

我推荐后一种方法。它的结果是更简单的代码。

关于java - Android:如何关闭从类返回到 Activity 的游标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10962585/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com