I have a problem and am not sure how to approach it. Activity in my application has several AsyncTask that access a single SQLiteOpenHelper . I initialize and open the helper in onCreate() , and I close it in onStop() . I also check if it was initialized in onResume() .
Since I published my application, I got a number of errors with a Null Exception in doInBackground , where I am trying to access the DB helper. I know this happens because the DB closes ( onStop() ) just before doInBackground is doInBackground .
My question is: where should I close the database connection? Is it correct to use one instance of the database helper in Activity and access it from multiple threads ( AsyncTasks )? Or should I use a separate instance of the secondary DB for each AsyncTask ?
This is a simplified skeleton of my activity:
public class MyActivity extends Activity{ private DbHelper mDbHelper; private ArrayList<ExampleObject> objects; @Override public void onStop(){ super.onStop(); if(mDbHelper != null){ mDbHelper.close(); mDbHelper = null; } } @Override public void onResume(){ super.onResume(); if(mDbHelper == null){ mDbHelper = new DbHelper(this); mDbHelper.open(); } } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); DbHelper mDbHelper = new DbHelper(this); mDbHelper.open(); } private class DoSomething extends AsyncTask<String, Void, Void> { @Override protected Void doInBackground(String... arg0) { objects = mDbHelper.getMyExampleObjects(); return null; } @Override protected void onPostExecute(final Void unused){
android sqlite android-asynctask sqliteopenhelper
Marqs
source share