如何从资产重新创建房间数据库? [英] How To recreate Room Database From Assets?

查看:30
本文介绍了如何从资产重新创建房间数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在 Asset 文件夹中预加载了数据库,它包含所有数据,当我在 Asset 中编辑我的数据库并增加版本号并使用 fallbackToDestructiveMigration() 应用程序可以工作但它丢失了我想要的所有数据知道如何使用 fallbackToDestructiveMigration() 从资产中重新创建有空间的数据库,然后将所有表从资产复制到新数据库我试过这个解决方案但没有工作,我也累了 正在迁移,但我的数据库有很多表和行,所以我不能这样做

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

我正在使用 Hilt 并提供这样的空间:

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()
}

推荐答案

您可以在创建时使用初始值预先填充它

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()

这篇关于如何从资产重新创建房间数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆