Skip to content
Advertisement

Room database reset to default values which was set by prepopulating database when clearing app from background

I have a database which is prepopulated with some tables which is working fine. I have prepopulated my db. like this

 Room.databaseBuilder(
        get(),
        AppDatabase::class.java,
        APP_DATABASE
         )
        .createFromAsset("app.db")
        .fallbackToDestructiveMigration()
        .build()

the problem I am facing is that. when user adds his own data it got inserted correctly and displayed on my screen. when I move app to the background and remove it from there and reopen the application. I don’t se my data and only the default data is present there.

any help would be appreciated.

Advertisement

Answer

I faced same issue – you just need to remove fallbackToDestructiveMigration() from your code
finally your code should look like

    @Volatile
    private var INSTANCE: AppDatabase? = null

    fun getDatabase(
        context: Context
    ): AppDatabase {

        return INSTANCE ?: synchronized(this) {
            val instance = Room.databaseBuilder(
                context.applicationContext,
                AppDatabase::class.java,
                DATABASE_NAME
            )
                .allowMainThreadQueries()
                .createFromAsset("databases/yourdb.db")
                .build()
            INSTANCE = instance
 
            instance
        }
    }
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement