0

I'm writing a database adapter class for an android app and plan to create table specific adapter classes as well. I'm going to be structuring the whole thing like like Shawn has it laid out in this post. Having multiple database helper classes seems redundant to me so I was wondering if it is possible to reference one database helper class instead of creating multiple ones. Here's the section I'm talking about:

public static class DatabaseHelper extends SQLiteOpenHelper {
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(DATABASE_CREATE);
        }
        catch (SQLException ex){
            ex.printStackTrace();
        }
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS Exercise");
        onCreate(db);
    }
}
Community
  • 1
  • 1
Greener
  • 1,327
  • 3
  • 13
  • 19

1 Answers1

0

I've discovered solution which looks quite good for me, please consider it. Create a kind of base database helper and create all tables there like

public static class BaseDbHelper extends SQLiteOpenHelper {
    BaseDbHelper (Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db) {
        //Create all tables here
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        //Drop all tables here
        onCreate(db);
    }
}

Then you can inherit from BaseDbHelper and create a specific methods for specific table. In this case you wont duplicate code and wont miss initialization whichever helper you call first.

Sergey Dmitriev
  • 454
  • 3
  • 13