Ramprasad
Ramprasad

Reputation: 8071

How to close Database resources in Application multiple Activities,fragments and Cursor Loaders

DBHelper.java

public class DBHelper extends SQLiteOpenHelper{

    public DBHelper(Context context) {
        super(context, DBConstants.DATABASE_NAME, null,DBConstants.DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(DBConstants.CREATE_LOGINTABLE);
        db.execSQL(DBConstants.CREATE_DATA_TABLE);
        db.execSQL(DBConstants.CREATE_LATEST_DATA_TABLE);
        db.execSQL(DBConstants.CREATE_ALERTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(DBConstants.DELETE_LOGINTABLE);
        db.execSQL(DBConstants.DELETE_DATA_TABLE);
        db.execSQL(DBConstants.DELETE_LATEST__DATA_TABLE);
        db.execSQL(DBConstants.DELETE_ALERTS_TABLE);
        onCreate(db);
    }

    @Override
    public synchronized void close() {
        super.close();
    }
}

Class1 (One of my Activity or Fragment in Application):

DBHelper myDbHelper=new DBHelper(context);
SQLiteDatabase myDB = myDbHelper.getWritableDatabase();

Cursor c1= myDB.query(DBConstants.LATEST_DATA_TABLE,mycolumns, null, null, null, null, null);
  /* is it correct */
c1.close();
myDB.close();
myDbHelper.close();
/* is it correct */

Class2 (One of my Activity or Fragment in Application):

DBHelper myDbHelper=new DBHelper(context);
SQLiteDatabase myDB = myDbHelper.getWritableDatabase();

Cursor c1= myDB.query(DBConstants.LATEST_DATA_TABLE,mycolumns, null, null, null, null, null);

/* is it correct */
c1.close();
myDB.close();
myDbHelper.close();
/* is it correct */

Here, shall i want to close all c1,myDB,myDbHelper objects or closing c1 and myDbHelper is enough? Which is the best practice ?

Upvotes: 0

Views: 715

Answers (1)

kdehairy
kdehairy

Reputation: 2730

  • myDbHelper.close() closes the database internally. so no need to call myDb.close.
  • and of course, c1.close() is a best practice you want to get used to it.

code:

try {
    //your database queries.
} catch (...) {

} finally {
    if (cursor != null && !cursor.isClosed()) {
        c1.close();
    }
    myDbHelper.close();
}

the finally block will make sure these resources are released whatever happens.

Upvotes: 1

Related Questions