将Android应用程序从SQLiteOpenHelper迁移到Room

时间:2018-05-03 10:42:17

标签: android kotlin android-sqlite android-room

我正在尝试将我的应用程序的数据库从SQLiteOpenHelper迁移到RoomDatabase,但由于我的项目非常庞大,我希望逐步完成,而不会破坏所有内容(因为使用了数据库)到处)。我的数据库有3个表:filessharedFilesunuploadedFiles,我只想迁移unuploadedFiles才能使用会议室

我有两个问题

  • 这真的有效吗?我可以将SQLiteOpenHelper和RoomDatabase与同一个数据库一起使用吗?

  • 我当前的数据库版本是8,当我迁移到Room时,我的迁移应该是8到9还是从1到2?

以下是一些代码:

我有一个dbHelper类,它处理对数据库的请求

class DBHelper extends SQLiteOpenHelper {
  private static final int DATABASE_VERSION = 8;
  private static final String DATABASE_NAME = "FilesDatabase";

  private static final String TABLE_FILES = "files";
  private static final String TABLE_SHARED = "sharedfiles";
  private static final String TABLE_UNUPLOADED = "unuploadedfiles";

  ...

}

现在我添加了FilesDatabase,它实现了RoomDatabase

@Database(entities = [(UnuploadedFile::class)], version = 2)
abstract class FilesDatabase : RoomDatabase() {

    abstract fun unuploadedFileDao(): UnuploadedFileDao

    companion object {

        private val MIGRATION_1_2: Migration = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
            }
        }

        @Volatile
        @JvmStatic
        private var INSTANCE: FilesDatabase? = null

        fun getInstance(context: Context): FilesDatabase =
            INSTANCE ?: synchronized(this) {
                INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
            }

        private fun buildDatabase(context: Context) =
            Room.databaseBuilder(context.applicationContext,
                FilesDatabase::class.java, "FilesDatabase.db")
                .addMigrations(MIGRATION_1_2)
                .build()
    }
}

和我的LocalFilesDataSource是UnuploadedFileDao和旧的dbHelper

class LocalFilesDataSource(context: Context,
                           private val unuploadedFileDao: UnuploadedFileDao) : FilesDataSource {

    companion object {
        private var INSTANCE: LocalFilesDataSource? = null

        @JvmStatic
        fun getInstance(context: Context, unuploadedFileDao: UnuploadedFileDao): LocalFilesDataSource {
            val result = INSTANCE ?: LocalFilesDataSource(context, unuploadedFileDao)
            INSTANCE = result
            return result
        }
    }

    private val dbHelper: DBHelper = DBHelper(context)
    ...
}

现在当我想向unuploadedFiles表发出请求时,我调用了UnuploadedFilesDao方法:

override fun addUnuploadedFile(userName: String, fileName: String) {
    unuploadedFileDao.insertUnuploadedFile(UnuploadedFile(userName, fileName))
}

当我想向其他表发出请求时,我调用dbHelper:

override fun insertFile(path: String?, filename: String?, serverModifiedDate: Date?, localModDate: Date?): Long =
    dbHelper.insertFile(path, filename, serverModifiedDate, localModDate)

0 个答案:

没有答案