gpt4 book ai didi

java - SQLite 连接对象泄露 - Android

转载 作者:IT王子 更新时间:2023-10-29 06:20:24 24 4
gpt4 key购买 nike

我正在制作我的第一个 Android 应用程序,我首先学习了一些 sqlite 教程,这些教程教我使用扩展 SQLiteOpenHelper 的 databaseHelper。所以我的 databaseHelper 确实扩展了 SQLiteOpenHelper。我在 Logcat 中收到了一个 sqlite 连接泄漏警告,因此想要一些关于如何修复该问题的建议。

我收到这个错误:

02-01 21:39:50.740: W/SQLiteConnectionPool(32061): A SQLiteConnection object for database '/data/data/com.btf271.fashionassistant/databases/clothingManager' was leaked!  Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.

在发生泄漏的地方调用我的 databaseHelper 函数:

 public List<Sticker> getObjectsByGenderAndCategory(String gender, String category) {
List<Sticker> objects = new ArrayList<Object>();
String selectQuery = String.format(
"SELECT * FROM %s WHERE %s = \"%s\" AND %s = \"%s\"",
TABLE_OBJECT, KEY_GENDER, gender, KEY_CATEGORY, category);

Log.e(LOG, selectQuery);

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
try{
// looping through all rows and adding to list
if (c.moveToFirst()) {
do {
Object o = createClothingItemJavaObject(c);

// adding to object list
objects.add(o);
} while (c.moveToNext());
}
}finally {
c.close();
db.close();
}
return objects;
}

我找到了 this which I will try tomorrow. It's late .

谢谢。

最佳答案

我所做的只是implement this answer to a similar question现在它不显示 SQL 连接对象泄漏错误。我怎么推荐都不为过。实现和工作只花了几分钟。

代码如下:

public class DatabaseHelper extends SQLiteOpenHelper { 

private static DatabaseHelper mInstance = null;

private static final String DATABASE_NAME = "database_name";
private static final String DATABASE_TABLE = "table_name";
private static final int DATABASE_VERSION = 1;

public static DatabaseHelper getInstance(Context ctx) {

// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
// See this article for more information: http://bit.ly/6LRzfx
if (mInstance == null) {
mInstance = new DatabaseHelper(ctx.getApplicationContext());
}
return mInstance;
}

/**
* Constructor should be private to prevent direct instantiation.
* make call to static factory method "getInstance()" instead.
*/
private DatabaseHelper(Context ctx) {
super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
}
}

关于java - SQLite 连接对象泄露 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21496221/

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