import androID.content.Contextimport androID.util.Logimport androIDx.work.Workerimport androIDx.work.WorkerParametersimport com.dmitrysimakov.gymlab.data.GymLabDbimport com.dmitrysimakov.gymlab.data.entity.Trainingimport com.Google.gson.Gsonimport com.Google.gson.reflect.Typetokenimport com.Google.gson.stream.JsonReaderimport javax.inject.Injectclass 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 @R_403_5983@Stream = context.assets.open("training.Json") JsonReader = JsonReader(@R_403_5983@Stream.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() } }}
我正在使用Dagger 2,所以不要这样做:Sunflower AppDatabase,我这样做:
import androID.arch.persistence.db.SupportsqliteDatabaseimport androID.arch.persistence.room.Roomimport androID.arch.persistence.room.RoomDatabaseimport androIDx.work.OneTimeWorkRequestBuilderimport androIDx.work.WorkManagerimport com.dmitrysimakov.gymlab.GymLabAppimport com.dmitrysimakov.gymlab.data.GymLabDbimport com.dmitrysimakov.gymlab.workers.SeedDatabaseWorkerimport dagger.Moduleimport dagger.ProvIDesimport 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()}
但我无法注入尚未创建的数据库.那么,我该如何访问dao?
解决方法 问题是我无法将我的数据库注入到Worker中.我在这里找到了解决方案: AndroidWorkerInjection 总结以上是内存溢出为你收集整理的Android系统.无法实例化工人全部内容,希望文章能够帮你解决Android系统.无法实例化工人所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)