Create new databases on runtime in app

529 Views Asked by At

I have a requirement to create a new database for each user in app, and to have multiple databases that change on user switching. Does any of the existing ORM's like GreenDAO, Storio, DbFlow, Realm or similar orm/libraries for Android support this or is it better to do this on foot, define each table and fields by my self, and use Sqlitedbhelper to generate each database from scratch?

2

There are 2 best solutions below

1
On

I've used greenDAO several times and this looks easy with it. You can take a look here.

Basically, you can specify by name what db do you want to use when you init the DaoMaster like this:

DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "your-db-name", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession daoSession = daoMaster.newSession();

// After the initialization, you can get your DAO's and start working
SomeDao someDao = daoSession.getSomeDao();

I don't know if you are familiar with greenDAO, but all the needed classes are automatically generated using a generator module. You could find here a good tutorial explaining how to use it with Android Studio.

5
On

As StorIO developer, I will answer about support of multiple databases in StorIO:

It's possible, StorIO does not limit you in the number of databases you work with, just create as much StorIOSQLite instances as you need and pass unique SQLiteOpenHelper that'll work with different DBs to each instance of StorIOSQLite. The only recommendation from our team — use one instance of StorIOSQLite per DB.

According to the documentation, GreenDAO and DbFlow should be able to work with multiple databases.

Looks like Realm won't allow you to use multiple databases since it's a singleton in their SDK: Realm.getInstance(context). Edit: Realm can handle multiple DBs (see comments to the answer).