0

In my already created and deployed application, I've created a database MainDB, using a single class file which extended SQLiteOpenHelper, viz.

public class BaseSQLiteOpenHelper extends SQLiteOpenHelper {

    private final static String DATABASE_NAME = "MainDB";
    ....
    ....
}

Issue is I've tied this class, too much to a particular functionality.

Now I'm adding a totally new module in application, which will also interact with DB, but with different new tables.

Issue is I can't use the same class, as it is conflicting in more than one way. And even if I redesign the code, it will only add complexity from functional/understanding point of view.

So, I've decided to use same DB, but different tables.

Now I've already created DB in BaseSQLiteOpenHelper class.

So, how can I create new tables in seprate class using same DB?

One approach is to use separate Database as well, Or,

Create my new table in onCreate() in BaseSQLiteOpenHelper class only (issue with this is mentioning new table in same class seems awkward, as this class has nothing to do with my new table).

Please suggest.

Thank You

reiley
  • 3,759
  • 12
  • 58
  • 114

1 Answers1

2

First check the current database version for this database

private final static String DATABASE_NAME = "MainDB";
private static final int DATABASE_VERSION = 1;

public BaseSQLiteOpenHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

and increment the database version(DATABASE_VERSION), and add your new table query in on Upgrade and oncreate method like below.

@Override
public void onCreate(SQLiteDatabase db) {
      db.execSQL("old query no need to change");
      db.execSQL("Create your new table here");
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    if (oldVersion < 2) {
       db.execSQL("Create your new table here as well this for update the old DB");
    }
}

Done!!!

Muthukrishnan Rajendran
  • 11,122
  • 3
  • 31
  • 41