RoomDatabase.Callback没有被调用

时间:2018-12-05 07:33:08

标签: android

我使用LiveData + ViewModel + Repository + Dao创建数据库实例,但是不调用RoomDatabase.Callback OnCreate和OnOpen。有什么想法吗?

  @Database(entities = [(Parking::class)], version = 1, exportSchema = false)
    abstract class ParkingDb : RoomDatabase() {

        abstract fun parkingDao(): parkingDao

        companion object {
            // For Singleton instantiation
            @Volatile private var instance: ParkingDb? = null

            fun getInstance(context: Context): ParkingDb {
                return instance ?: synchronized(this) {
                    instance ?: buildDatabase(context).also { instance = it }
                }
            }

            // Create and pre-populate the database. See this article for more details:
            // https://medium.com/google-developers/7-pro-tips-for-room-fbadea4bfbd1#4785
            private fun buildDatabase(context: Context): ParkingDb {
                return Room.databaseBuilder(context, ParkingDb::class.java, DATABASE_NAME)
                    .addCallback(object : RoomDatabase.Callback() {
                        override fun onCreate(db: SupportSQLiteDatabase) {
                            super.onCreate(db)
                            val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
                            WorkManager.getInstance().enqueue(request)
                        }

                        override fun onOpen(db: SupportSQLiteDatabase) {
                            super.onOpen(db)
                            val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
                            WorkManager.getInstance().enqueue(request)
                        }
                    })
                    .build()
            }

        }
    }

---- SeedDatabaseWorker类----

class SeedDatabaseWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
    private val TAG by lazy { SeedDatabaseWorker::class.java.simpleName }

    override fun doWork(): Result {
        val parkingType = object : TypeToken<List<Parking>>() {}.type
        var jsonReader: JsonReader? = null

        return try {
            val inputStream = applicationContext.assets.open(PARKING_DATA_FILENAME)
            jsonReader = JsonReader(inputStream.reader())
            val parkingList: List<Parking> = Gson().fromJson(jsonReader, parkingType)
            val database = ParkingDb.getInstance(applicationContext)
            database.parkingDao().insert(parkingList)
            Result.SUCCESS
        } catch (ex: Exception) {
            Log.e(TAG, "Error seeding database", ex)
            Result.FAILURE
        } finally {
            jsonReader?.close()
        }
    }
}

0 个答案:

没有答案