SQLite connection object leaked - Android

泄露秘密 提交于 2019-11-30 02:16:34
user3164083

All I did was implement this answer to a similar question and now it doesn't show the SQL connection object leak error. I cannot recommend this enough. It only took a few minutes to implement and worked.

Here is the code:

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);
  }
}

I fixed this by adding

@Override
protected void finalize() throws Throwable {
    this.close();
    super.finalize();
}

to my SQLiteOpenHelper extended class

Match each call to getReadableDatabase() and getWritableDatabase() to a corresponding close() on the same database object.

For example, your getAllClothingItemsByGenderAndCategory() calls getReadableDatabase() but does not close() it. Add db.close() after c.close().

Your closeDB() makes no sense since it gets a new reference to the database with getReadableDatabase() and closes just that. It does nothing to close any existing database connection.

Each time you open a database(readable or writable) and cursor which uses memory resources has to be deallocated by using ".close();" after its usage ends in each database function.. by your_database object.close(); and cursor object.close();

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!