简体   繁体   中英

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?

Maybe you could but this approach is wrong for several reasons. You dont make separate databases for users you make tables with relations to each other, each row is an entry for a user.
Some tables have a one-to-many relationship like a table that holds order numbers. One user may have many orders. Or the table may have a one-to-one relationship like a user profile. What it breaks down to is, each user has a unique entry and ID, that ID would relate to other tables with their data. You use the ID for the logged in person to get their data. Beyond that, you really shouldnt be storing other peoples data in your app, what is the situation where you feel multiple people will be using the same phone for the app? The ideal situation is to have a cloud based server/database that you get your data from so only the current users data is retrieved.
The final reason you dont do multiple databases is that if you want to add a new field you would have to update every DB created instead of just one.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM