So I want to have one database instance for all application activities.
I found the following code:
public class MyApplication extends Application {
private static SQLiteDatabase mDB = null;
@Override
public void onCreate() {
super.onCreate();
DataBaseOpenHelper m_OpenHelper = new DataBaseOpenHelper( this );
mDB = m_OpenHelper.getWritableDatabase();
}
public static SQLiteDatabase getDB() {
return mDB;
}
}
I don`t understand when I can close SQLiteDatabase instance.
This was an issue for me when I first started out with Android, as there aren’t many tutorials on the web that describe how to correctly allow access to your database across the entire application (don’t ask me why). Here’s some sample code that exhibits three possible approaches.
Approach #1: subclassing `Application`
If you know your application won’t be very complicated (i.e. if you know you’ll only end up having one subclass of
Application), then you can create a subclass ofApplicationand have your main Activity extend it. This ensures that one instance of the database is running throughout the Application’s entire life cycle.Approach #2: have `SQLiteOpenHelper` be a static data member
This isn’t the complete implementation, but it should give you a good idea on how to go about designing the
DatabaseHelperclass correctly. The static factory method ensures that there exists only one DatabaseHelper instance at any time.Approach #3: abstract the SQLite database with a `ContentProvider`
This is the approach I would suggest. For one, the new
LoaderManagerclass relies heavily on ContentProviders, so if you want an Activity or Fragment to implementLoaderManager.LoaderCallbacks<Cursor>(which I suggest you take advantage of, it is magical!), you’ll need to implement aContentProviderfor your application. Further, you don’t need to worry about making a Singleton database helper with ContentProviders. Simply callgetContentResolver()from the Activity and the system will take care of everything for you (in other words, there is no need for designing a Singleton pattern to prevent multiple instances from being created).Hope that helps!