Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room with Multi user Database in Single android App

Can we have a multiple databases in single android App using Room? I want to create a new database for every single user. If user1 logged in I have to create a Database for that user like UserDB1, If any new account added I have to create a another Database for that user like UserDb2. If account switch happened between that accounts I should access the user specific Database.How can i achieve that?

like image 578
karthi Avatar asked Jan 01 '23 14:01

karthi


1 Answers

I did that like below,

    private static AppDatabase buildDatabase(final Context appContext, int userId) {
    return Room.databaseBuilder(appContext, AppDatabase.class, DATABASE_NAME + "_" + userId)
            .addCallback(new Callback() {
                @Override
                public void onCreate(@NonNull SupportSQLiteDatabase db) {
                    super.onCreate(db);

                }
            })
        .build();
}

I understand your requirement totally. There are 3 ways, (Let's say only need a table userTable, but actually we have more.)

  1. Create a database for each login user. (You asked, I also used it)
  2. Only a database, but create a table for each user, such as userTable_1. (It seems that Room can't support it )
  3. Only a database and a table for all users, so we have to add a extra column user_id to the table; if we have 20 table, we have to add "user_id" to all 20 tables. (We did it in the backend development at the most time; but in the case, I really do NOT prefer to this one)
like image 124
Stony Avatar answered Jan 05 '23 04:01

Stony