1

I have preloaded database in Asset folder and it contain all data , when i Edit my database in Asset and increase version number and using fallbackToDestructiveMigration() app is work but it lose all data i want to know how to recreate database with room from assets using fallbackToDestructiveMigration() and then coping all tables from assets to new database i tried this solution but didn't work and i tired also Migrating but my database have a lot of tables and rows so i can't do that

i'm using Hilt and provides room like this :

@Singleton
@Provides
fun provideMyDataBase(mApplication: Application): MyDataBase {
    return Room.databaseBuilder(mApplication, MyDataBase::class.java, DATABASE_NAME)
        .createFromAsset(DATABASE_NAME)
        .fallbackToDestructiveMigration()
        .build()
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Ayoub Benzahia
  • 333
  • 4
  • 14
  • Make sure the prepopulated database has the same version number and the same table structure as the current database. You can DB Browser to updated the DB, use the Database inspector provided by Android Studio to compare both versions. I was facing the similar and resolved it by following above steps. – Alpha 1 Dec 29 '20 at 16:00
  • @AlphaOne My preloaded has not version table and all tables are same structure beacuse when i clear data it works fine but when update my app the new version not work the database empty so i'm trying to find a way when i increase version number the database also copy data from assets to and delete previous tables – Ayoub Benzahia Dec 29 '20 at 16:16

1 Answers1

0

You can prepopulate it with your initial values when its created

Room.databaseBuilder(context.applicationContext,
    DataDatabase::class.java, "Sample.db")
    // prepopulate the database after onCreate was called
    .addCallback(object : Callback() {
        override fun onCreate(db: SupportSQLiteDatabase) {
            super.onCreate(db)
            // moving to a new thread
            ioThread {
                getInstance(context).dataDao()
                                    .insert(PREPOPULATE_DATA)
            }
        }
    })
    .build()
Adarsh Binjola
  • 216
  • 2
  • 10