SQLite connection object leaked - Android SQLite connection object leaked - Android sqlite sqlite

SQLite connection object leaked - Android


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

@Overrideprotected 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.