9

I am trying to see which of these implementation is better for accessing sqlite database in Android Applications

Implementation 1

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.

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) {}

    }

Implementation 2

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.

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

    }

}

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.

I am using Content Providers always if that matters.

Thank you

achie
  • 4,716
  • 7
  • 45
  • 59
  • Similar http://stackoverflow.com/questions/6092631/static-class-vs-singleton-class – wtsang02 Feb 28 '13 at 02:06
  • 2
    I am aware of how the static inner class behaves. I am looking for an Android implementation specific answer which helps me understand the advantages/disadvantages when it comes to opening/accessing/closing database and threading. – achie Feb 28 '13 at 02:09

1 Answers1

1

I do neither. I have a non-static class that extends SqliteOpenHelper. Whenever I need the db, I open it by creating a new DBHelper instance, do what I need to do with it, and immediately close it, reopening it later only when I need it. It's possible to run into the case with this implementation where two sections of code try to modify the db at the same time. To avoid that, wrap every method in synchronized blocks. I haven't had any issues with this approach.

Jason Robinson
  • 31,005
  • 19
  • 77
  • 131
  • Yes that sure is another way but then i have to deal with thread syncronization everywhere. Perhanps someone might be able to weigh this approach also along with the top two. But For now I am interested in only one of the top two since I do not want to deal with syncronization throughout my code. Thank you though. – achie Feb 28 '13 at 02:11
  • @achie my last 2 sentences address that. If you wrap all your methods within the `DBHelper` class then you won't have synchronization issues outside of the class. – Jason Robinson Feb 28 '13 at 02:15
  • Bad idea ... What will happend if you had 2 Fragments ... one is ListFragment using CursorAdapter (so you CANT close Helper because it will close Cursor, too) and second Fragmet need to create new Helper for fx. save date ... – Selvin Feb 28 '13 at 02:21
  • @Selvin There's not an issue with that due to the synchronization. You don't _have_ to close the helper. – Jason Robinson Feb 28 '13 at 02:24
  • Are you sure that we can have multiple instances of the same DbHelpers opened? I dont think so ... – Selvin Feb 28 '13 at 02:29
  • @Selvin Yeah, why not? As long as you're not access the database at the same time (fixed via synchronization), there's not an issue. It's the same problem you'd have with any approach. – Jason Robinson Feb 28 '13 at 03:08
  • Weeeeell, that's a bad answer regarding your idea of how `synchronized` works. Synchronizing works on a single instance, so either you have to manually write code to use that single (singleton or static) lock object, or your `synchronized`keyword in the method declaration is worth nothing. – Bondax Jun 07 '16 at 13:52