Search code examples
androidandroid-sqlitesqliteopenhelper

Closing DBHelper in Application class


With reference to Android: Documentation for using SQLite database, we should be closing the reference to the DBHelper in the onDestroy of the activity :

@Override
protected void onDestroy() {
    mDbHelper.close();
    super.onDestroy();
}

But I want to use the DBHelper object in the Application class :

public class UnifiedApplication extends Application {

    // Database helper
    public UnifiedAppDBHelper mDbHelper;

    @Override
    public void onCreate() {
        mDbHelper = new UnifiedAppDBHelper(this);
        super.onCreate();
    }
}

I thought about adding the mDbHelper.close() in the onTerminate() of the Application class, but as mentioned in the Documentation, onTerminate() will never be called on a production device. Where should I close the mDbHelper object?


Solution

  • You don't have to close your mDbHelper object. Your database session will live as long as Application object lives and this is fine.

    Here you can find more about it.