Search code examples
androidmultithreadingsqlitesingletonsqliteopenhelper

Using same instance of SQLiteDatabase across different instances of SQLiteOpenHelper


I need multiple tables in my application. For this I've created separate subclasses of SQLiteOpenHelper to insert/remove/update data for different tables. My question is how can I make sure all these subclasses uses same instance of SQLiteDatabase across the entire code. Though I've made each subclass a singleton. However, I couldn't work around the issue of using a common SQLiteDatabase instance across the entire code.

PS: I don't want to use a ContentPovider or create a single SQLiteOpenHelper subclass as this would complicate my code.


Solution

  • I don't really see where you're struggling at using a common SQLiteOpenHelper. You just have to duplicate what you do for one table ! Create a custom class that extends SQLiteOpenHelper and do the duplication.

    public class SQLiteCustomBase extends SQLiteOpenHelper {
    
        private static final String CREATE_BDD_1 = "CREATE TABLE ...";
        private static final String CREATE_BDD_2 = "CREATE TABLE ...";
    
        public SQLiteCustomBase(Context context, String name, CursorFactory factory, int version) {
            super(context, name, factory, version);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_BDD_1);
            db.execSQL(CREATE_BDD_2);
        }
    
        @Override
        public void onOpen(SQLiteDatabase db) {}
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE " + Vars.TABLE_1 + ";");
            db.execSQL("DROP TABLE " + Vars.TABLE_2 + ";");
            onCreate(db);
        }
    }
    

    and then in the class where you perform some database actions :

    public class HandlerClass {
        private SQLiteDatabase db;
        private SQLiteCustomBase customBase;
    
        public HandlerClass(Context context){
            customBase = new SQLiteCustomBase(context, Vars.NAME_DB, null, Vars.VERSION_DB);
        }
    
        public void open(){
            db = customBase.getWritableDatabase();
        }
    
        public void openForRead(){
            db = customBase.getReadableDatabase();
        }
    
        public void close(){
            db.close();
        }
    
        public SQLiteDatabase getDB(){
            return db;
        }
    }
    
    void myMethods()
    {
        bdd.insert(Vars.TABLE_1, null, values);
        bdd.insert(Vars.TABLE_2, null, values);
    }
    etc.