title: Android AsyncTask and SQLite DB instance
body: <p>I have a problem and I am not sure how to approach it. An activity in my app has multiple <code>AsyncTask</code>s which access single <code>SQLiteOpenHelper</code>. I initialize and open the helper in <code>onCreate()</code> and I am closing it in <code>onStop()</code>. I also check if it has been initialized in <code>onResume()</code>.</p>
  
  <p>Since I have published my app I received number of errors with Null Exception in <code>doInBackground</code> where I try to access the DB helper. I know that this is happens because the DB is closed ( <code>onStop()</code> ) just before the <code>doInBackground</code> is called, fair enough.</p>
  
  <p>My question is, where should I close the DB connection? Is it right to use a single instance of the DB helper in the Activity and access it from multiple threads(<code>AsyncTasks</code>)? Or I should use separate DB helper instance for each <code>AsyncTask</code>?</p>
  
  <p>This is a simplified skeleton of my activity:</p>
  
  <pre><code>public class MyActivity extends Activity{
      private DbHelper mDbHelper;
      private ArrayList&lt;ExampleObject&gt; 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&lt;String, Void, Void&gt; {
  
          @Override
          protected Void doInBackground(String... arg0) {
              objects = mDbHelper.getMyExampleObjects();
              return null;
          }
  
          @Override
          protected void onPostExecute(final Void unused){
              //update UI with my objects
          }
      }
  
      private class DoSomethingElse extends AsyncTask&lt;String, Void, Void&gt; {
  
          @Override
          protected Void doInBackground(String... arg0) {
              objects = mDbHelper.getSortedObjects();
              return null;
          }
  
          @Override
          protected void onPostExecute(final Void unused){
              //update UI with my objects
          }
      }
  }
  </code></pre>