简体   繁体   English

Android Room 数据库迁移没有正确处理

[英]Android Room database Migration didn't properly handle

In my application, I am using a Room database.在我的应用程序中,我使用的是 Room 数据库。 Here to support the offline feature, I need to use the pre-populated database.这里为了支持离线功能,我需要使用预先填充的数据库。

So, what I need is, I have created one Room database with values, and put that database in the assets folder of the project and importing the database to my local.所以,我需要的是,我创建了一个带有值的 Room 数据库,并将该数据库放在项目的资产文件夹中并将数据库导入到我的本地。

Now everything works fine.现在一切正常。

Now, for some reason, I am adding one more column to my local database ( not the external which is in assets folder ), but it gives me the following error.现在,出于某种原因,我在本地数据库中再添加一列(不是资产文件夹中的外部数据库),但它给了我以下错误。

java.lang.IllegalStateException: Migration didn't properly handle java.lang.IllegalStateException:迁移没有正确处理

I have also added the migration.我还添加了迁移。

Following is my code for the database.以下是我的数据库代码。

@Database(
entities = arrayOf(ModelCategories::class, ModelApps::class),
version = 4,
exportSchema = false)

abstract class LauncherDatabase : RoomDatabase() {

abstract fun categoriesDAO(): DAOCategories
abstract fun appsDAO(): DAOApps

companion object {
    // Singleton prevents multiple instances of database opening at the
    // same time.
    @Volatile
    private var INSTANCE: LauncherDatabase? = null

    /*
        When there is change in Databse structure new migration should be there
     */
    @JvmField
    val MIGRATION_3_2: Migration = object : Migration(3, 4) {
        override fun migrate(database: SupportSQLiteDatabase) {
        }
    }

    fun getDatabase(context: Context): LauncherDatabase {
        val tempInstance = INSTANCE
        if (tempInstance != null) {
            return tempInstance
        }
        synchronized(this) {
            val instance = Room.databaseBuilder(
                context.applicationContext,
                LauncherDatabase::class.java,
                "launcher_database"
            ).createFromAsset("databases/launcher_database.db")
                .addMigrations(LauncherDatabase.MIGRATION_3_2)
                .build()
            INSTANCE = instance
            return instance
        }
    }
}}

Note:- The database version of the external assets database is 3. So, after adding one column to Model class, I am increasing the current database version to 4.注意:- 外部资产数据库的数据库版本是 3。所以,在 Model 类中添加一列后,我将当前数据库版本增加到 4。

Thanks in advance.提前致谢。

inside override fun migrate you have to write里面覆盖乐趣迁移你必须写

database.execSQL("ALTER TABLE your_table_name ADD COLUMN column_name type");

where type will be Integer in case of int, TEXT in case of String or custom data type etc. If you can tell your column data type then I can add actual code.在 int 的情况下,type 将是 Integer,在 String 或自定义数据类型等的情况下,type 将是 TEXT。如果您能告诉您的列数据类型,那么我可以添加实际代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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