在扩展AsyncTask的类中使用带有SQLiteOpenHelper的WeakReference上下文

我正在将上下文引用从调用的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);
  }

现在,Android Studio显示以下错误:

在扩展AsyncTask的类中使用带有SQLiteOpenHelper的WeakReference上下文

我该如何解决?

imzijian 回答:在扩展AsyncTask的类中使用带有SQLiteOpenHelper的WeakReference上下文

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2821781.html

大家都在问