OK to have one instance of SQLiteOpenHelper shared by all Activities in an Android application?

Having a single SQLiteOpenHelper instance can help in threading cases. Since all threads would share the common SQLiteDatabase synchronization of operations is provided.

Up vote 2 down vote favorite 1 share g+ share fb share tw.

Android sqlite application sqliteopenhelper link|improve this question asked Jan 17 at 1:13Julian7341617 64% accept rate.

Having a single SQLiteOpenHelper instance can help in threading cases. Since all threads would share the common SQLiteDatabase, synchronization of operations is provided. However, I wouldn't make a subclass of Application.

Just have a static data member that is your SQLiteOpenHelper. Both approaches give you something accessible from anywhere. However, there is only one subclass of Application, making it more difficult for you to use other subclasses of Application (e.g. , GreenDroid requires one IIRC).

Using a static data member avoids that. However, do use the Application Context when instantiating this static SQLiteOpenHelper (constructor parameter), so you do not leak some other Context. And, in cases where you aren't dealing with multiple threads, you can avoid any possible memory leak issues by just using one SQLiteOpenHelper instance per component.

However, in practice, you should be dealing with multiple threads (e.g. , a Loader), so this recommendation is only relevant for trivial applications, such as those found in some books... :-).

I actually used your LoaderEx classes and Advanced Android book to learn how to move database access off the UI thread. Thank you so much for both. They were a huge help.

– Julian Jan 17 at 1:37.

CommonsWare is right on (as usual). Expanding on his post, here is some sample code that illustrates three possible approaches. These will allow access to the database throughout the application.

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 of Application and have your main Activity extend it. This ensures that one instance of the database is running throughout the Application's entire life cycle.

Public class MainApplication extends Application { /** * see NotePad tutorial for an example implementation of DataDbAdapter */ private static DataDbAdapter mDbHelper; /** * Called when the application is starting, before any other * application objects have been created. Implementations * should be as quick as possible... */ @Override public void onCreate() { super.onCreate(); mDbHelper = new DataDbAdapter(this); mDbHelper.open(); } /** * Called when the application is stopping. There are no more * application objects running and the process will exit.

* Note: never depend on this method being called; in many * cases an unneeded application process will simply be killed * by the kernel without executing any application code... */ @Override public void onTerminate() { super.onTerminate(); mDbHelper.close(); mDbHelper = null; } public static DataDbAdapter getDatabaseHelper() { return mDbHelper; } } 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 DatabaseHelper class correctly. The static factory method ensures that there exists only one DatabaseHelper instance at any time. /** * create custom DatabaseHelper class that extends SQLiteOpenHelper */ public class DatabaseHelper extends SQLiteOpenHelper { private static DatabaseHelper mInstance = null; private static final String DATABASE_NAME = "databaseName"; private static final String DATABASE_TABLE = "tableName"; private static final int DATABASE_VERSION = 1; private Context mCxt; public static DatabaseHelper getInstance(Context ctx) { /** * use the application context as suggested by CommonsWare.

* this will ensure that you don't accidentally leak an Activitys * context (see this article for more information: * http://developer.android.com/resources/articles/avoiding-memory-leaks.html) */ 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(context, DATABASE_NAME, null, DATABASE_VERSION); this. MCtx = ctx; } } Approach #3: abstract the SQLite database with a `ContentProvider` This is the approach I would suggest. For one, the new LoaderManager class relies heavily on ContentProviders, so if you want an Activity or Fragment to implement LoaderManager.

LoaderCallbacks (which I suggest you take advantage of, it is magical! ), you'll need to implement a ContentProvider for your application. Further, you don't need to worry about making a Singleton database helper with ContentProviders.

Simply call getContentResolver() 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!

Great code examples. Thanks Alex! – Julian Jan 17 at 2:44 1 Just thought I'd point out that CommonsWare's LoaderEx library shows how to use the LoaderManager.

LoaderCallbacks interface and Loaders when working directly with a SQLite database instead of a ContentProvider. Github.com/commonsguy/cwac-loaderex – Julian Jan 18 at 7:09 You need to call super.onCreate() from your override. Possibly the same for onTerminate() - not sure.

– Tommy Herbert Feb 15 at 15:47 oops, forgot about that... you need it for both methods. Fixed! – Alex Lockwood Feb 15 at 16:39 on second thought, there might not be a definite answer for onTerminate(), since the method might not even be called.

Including it seems safer though :) – Alex Lockwood Feb 15 at 16:44.

I have written MultiThreadSQLiteOpenHelper which is an enhanced SQLiteOpenHelper for Android applications where several threads might open and close the same sqlite database. Instead of calling close method, threads ask for closing the database, preventing a thread from performing a query on a closed database. If each thread asked for closing, then a close is actually performed.

Each activity or thread (ui-thread and user-threads) performs an open call on database when resuming, and asks for closing the database when pausing or finishing. Source code and samples available here: github.com/d4rxh4wx/MultiThreadSQLiteOpe....

Yes, that is the way you should go about it, having a helper class for the activities that need an instance of the Database.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions