I have a problem and I am not sure how to approach it. An activity in my app has multiple AsyncTasks which access single SQLiteOpenHelper. I initia
You don't need to manage db connection for each activity. You can do it in an instance of android.app.Application and access db using this instance. Something like this:
public class MyApplication extends Application {
// Synchronized because it's possible to get a race condition here
// if db is accessed from different threads. This synchronization can be optimized
// thought I wander if it's necessary
public synchronized static SQLiteDatabase db() {
if(self().mDbOpenHelper == null) {
self().mDbOpenHelper = new MyDbOpenHelper();
}
return self().mDbOpenHelper.getWritableDatabase();
}
public static Context context() {
return self();
}
@Override
public void onCreate() {
super.onCreate();
mSelf = this;
}
private static MyApplication self() {
if (self == null) throw new IllegalStateException();
return mSelf;
}
private MyDbOpenHelper mDbOpenHelper;
private static MyApplication mSelf;
}
This way you can be sure you Db is always accessible.
And yes, having one instance of Db helper is a good practice. Thread syncronisation is made for you by default.
You mentioned that you cancel the AsyncTask before closing the DB. But you should keep in mind that cancelling the AsyncTask just signals the task to be cancelled and you need to check isCancelled() in doInBackground() and do the needful to stop DB operations.
Before closing the DB, you then need to check getStatus() to be sure that the AsyncTask has stopped.
It is good to use a single DB Helper.
The problem is that when the user leaves the Activity the DB is closed but the AsyncTask may still run. So you should check that the DB is not null when you are trying to access it, and if it is null this may mean that your Activity was destroyed and cancel that task.