在Room中从一个版本迁移到另一个版本时,我们可以删除记录吗?

时间:2018-12-23 10:31:21

标签: android migration android-room

我试图删除一些为空的字段

val MIGRATE_7_8: Migration = object : Migration(7, 8) {
    override fun migrate(db: SupportSQLiteDatabase) {

        db?.execSQL("DELETE FROM LEG WHERE (field1 IS NULL) OR (field2 IS NULL) OR (field3 IS NULL) OR (field4 IS NULL) ")

    }

我因java.lang.IllegalStateException引起的异常

Logcats

Caused by java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/user/0/com.staralliance.navigator/databases/conciergeDb
       at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55)
       at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1663)
       at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1608)
       at android.arch.persistence.db.framework.FrameworkSQLiteDatabase.execSQL(FrameworkSQLiteDatabase.java:242)
       at com.staralliance.navigator.data.local.room.db.MigrationsKt$MIGRATE_7_8$1.migrate(Migrations.kt:57)
       at android.arch.persistence.room.RoomOpenHelper.onUpgrade(RoomOpenHelper.java:85)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.onUpgrade(FrameworkSQLiteOpenHelper.java:133)
       at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:299)
       at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:194)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:96)
       at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
       at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:233)
       at com.staralliance.navigator.data.local.room.dao.AirlineDao_Impl.airlines(AirlineDao_Impl.java:172)
       at com.staralliance.navigator.data.local.room.LocalRepository.loadFlights(LocalRepository.kt:200)
       at com.staralliance.navigator.data.web.AirlinesFetchTask.doInBackground(AirlinesFetchTask.kt:23)
       at com.staralliance.navigator.data.web.AirlinesFetchTask.doInBackground(AirlinesFetchTask.kt:14)
       at android.os.AsyncTask$2.call(AsyncTask.java:333)
       at java.util.concurrent.FutureTask.run(FutureTask.java:266)
       at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
       at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
       at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
       at java.lang.Thread.run(Thread.java:764)

1 个答案:

答案 0 :(得分:0)

数据库已关闭,这是在执行查询之前需要检查数据库是否打开的问题

if (!db.isOpen())
    db.open();