我想从assets文件夹中的json文件预先填充我的房间数据库。我遵循Google Sunflower sample。我复制了SeedDatabaseWorker类:
import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.dmitrysimakov.gymlab.data.GymLabDb
import com.dmitrysimakov.gymlab.data.entity.Training
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.stream.JsonReader
import javax.inject.Inject
class SeedDatabaseWorker(val context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
private val TAG = SeedDatabaseWorker::class.java.simpleName
@Inject lateinit var database: GymLabDb
override fun doWork(): Worker.Result {
val plantType = object : TypeToken<List<Training>>() {}.type
var jsonReader: JsonReader? = null
return try {
val inputStream = context.assets.open("training.json")
jsonReader = JsonReader(inputStream.reader())
val plantList: List<Training> = Gson().fromJson(jsonReader, plantType)
database.trainingDao().insert(plantList)
Worker.Result.SUCCESS
} catch (ex: Exception) {
Log.e(TAG, "Error seeding database", ex)
Worker.Result.FAILURE
} finally {
jsonReader?.close()
}
}
}
我用的是匕首2,所以我不这样做:Sunflower AppDatabase,而是这样做:
import android.arch.persistence.db.SupportSQLiteDatabase
import android.arch.persistence.room.Room
import android.arch.persistence.room.RoomDatabase
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.dmitrysimakov.gymlab.GymLabApp
import com.dmitrysimakov.gymlab.data.GymLabDb
import com.dmitrysimakov.gymlab.workers.SeedDatabaseWorker
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module(includes = [ViewModelModule::class])
class AppModule {
@Singleton
@Provides
fun provideDb(app: GymLabApp): GymLabDb {
return Room
.databaseBuilder(app, GymLabDb::class.java, "gymlab.db")
.addCallback(object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
val request = OneTimeWorkRequestBuilder<SeedDatabaseWorker>().build()
WorkManager.getInstance().enqueue(request)
}
})
.fallbackToDestructiveMigration()
.build()
}
@Singleton
@Provides
fun provideTrainingDao(db: GymLabDb) = db.trainingDao()
}
但我不能注入尚未创建的数据库。那么,我怎样才能接触到刀呢?
最佳答案
您的问题是SeedDatabaseWorker
仍然基于Worker()
,现在已弃用,因此需要使用Worker(Context, WorkerParameters)
此构造函数。
从another post查看我的答案,它将帮助您理解WorkManager
库。
编辑:
你现在可以查看向日葵演示中的Worker,它已经更新。