简体   繁体   中英

How to pre-populate data to table?

Recently I have found the article about Room db and there was first tip for pre-populating the data to database.

Is there currently some elegant way to pre-populate the data when the database is created?

I am using Dagger2, so the actual creation of the database is done quite easy.

@Module
class DatabaseModule{

    @Provides
    @Singleton
    fun provideObjectBox(context: Context): BoxStore =
        MyObjectBox.builder()
                .androidContext(context)
                .build()

}

And the way I am doing it now with the SharedPreferences. So I am just checking if it is the first set up of the database and than populating the database.

Also i guess when the question was created it was not possible there is a function added to the builder so you can simply call:

 MyObjectBox.builder()
            .initialDbFile(file)
            .androidContext(context)
            .build()

This will use the given file must contain all data in mdb format. I am using this feature for backuping user data so i dont have to create the file on my own.
As far as i know there is no easy posibility to create this file instead of creating objects and putting them in the boxStore.
I am copying the file with already existing data like this (not the pretty way though)

     val dbFile = File(File(File(activity.getFilesDir(), "objectbox"),  BoxStoreBuilder.DEFAULT_NAME), "data.mdb")

Just found the main contributer answered the same: https://stackoverflow.com/a/51765399/8524651

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