我正在将上下文引用从调用的Activity传递给处理我所有SQLite数据库事务的AsyncTask文件。我在LogCat中发现了以下警告:
W / SQLiteConnectionPool:数据库'grocery_database'的SQLiteConnection对象泄漏了!请修复您的应用程序,以正确结束正在进行的事务,并在不再需要数据库时将其关闭。W / System:资源无法调用关闭。
我读到最好使用对Context的弱引用,因为它允许对当前AsyncTask进行垃圾回收并防止内存泄漏。但是,我使用的SQLiteOpenHelper不会接受对上下文的弱引用。
public class UpdateDatabaseTask extends AsyncTask <Long, Void, Void>{
private long listItemId;
private String userInput;
private WeakReference<Context> weakContext;
private SQLiteOpenHelper databaseHelper;
public UpdateDatabaseTask(Context context, String userInput) {
weakContext = new WeakReference<>(context);
this.userInput = userInput;
}
@Override
protected Void doInBackground(Long... listItemIdArray) {
listItemId = listItemIdArray[0];
// SQLiteOpenHelper does not accept a weak reference
databaseHelper = new DatabaseHelper(weakContext);
}
我该如何解决?
解决方案:从以下位置更改代码
databaseHelper = new DatabaseHelper(weakContext);
到
Context context = weakContext.get();
if (context != null) {
databaseHelper = new DatabaseHelper(context);
}