title: Singleton vs a static inner class for Database Helper class in Android
body: <p>I am trying to see which of these implementation is better for accessing sqlite database in Android Applications</p>
  
  <h1>Implementation 1</h1>
  
  <p>Using DatabaseHelper classes extending SqliteOpenHelper and using singleton pattern. In some rare occasions I do see crashes because database being closed. Although a little irritating, I let them pass just because it was minor in the grand scheme of things and the number of projects I have.</p>
  
  <pre><code>public class DBHelper extends SQLiteOpenHelper {
  
          private static DBHelper instance;
  
          private final String CREATE_HEALTH_DATA_TABLE = "CREATE TABLE IF NOT EXISTS my_table ( " 
          + BaseColumns._ID   + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
          + MT_FIELD_NAME     + " TEXT NOT NULL );";
  
          private DBHelper getInstance(Context c) {
               if (instance == null) {
                    instance = new DBHelper(c);
               }
               return instance;
          }
  
          private DBHelper(Context c) {
               super(c, "my_database.sqlite", null, 0);
          }
  
          @Override
          public void onCreate(SQLiteDatabase db) {
              db.execSQL(CREATE_TABLE);
          }
  
          @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
  
      }
  </code></pre>
  
  <h1>Implementation 2</h1>
  
  <p>The other way of implementing this is to create the helper class as a static inner class within the Content Provider class. This is how it is done in the Notepad Example in the samples.</p>
  
  <pre><code>public class DataProvider extends ContentProvider {
  
      /*..Content provider implementation only dbhelper variable and onCreate are shown */
  
      private MTDBHelper dbHelper;
  
      @Override
      public boolean onCreate() {
           dbHelper = new DBHelper(getContext());
           return true;
      }
  
      private static class DBHelper extends SqliteOpenHelper {
  
      /// Implementation without making it a singleton
  
      }
  
  }
  </code></pre>
  
  <p>Which among these is a better or standard way of things and why. I am guessing it is the second approach as it is an inner private class but would like to have an expert opinion.</p>
  
  <p>I am using Content Providers always if that matters.</p>
  
  <p>Thank you</p>