I'm learning android development from Android_developer. while using CoroutinesWorker, I encountered a problem whilst working with Kotlin
Logcat
com.google.samples.apps.devbyteviewer E/WM-WorkerFactory: Could
not instantiate
com.google.samples.apps.devbyteviewer.work.RefreshDataWorker
java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at
androidx.work.WorkerFactory.createWorkerWithDefaultFallback(Worker
Factory.java:96)
at
androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:
244)
at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:136)
The Application class from where I instantiate workmanager.
Application class
package com.google.samples.apps.devbyteviewer
import android.app.Application
import androidx.work.*
import
com.google.samples.apps.devbyteviewer.work.RefreshDataWorker
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.concurrent.TimeUnit
As I have read in related posts, my worker class is a top level class and in an independent file.
Worker class
package com.google.samples.apps.devbyteviewer.work
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.google.samples.apps.devbyteviewer.database.getDatabase
import com.google.samples.apps.devbyteviewer.repository.VideosRepository
import retrofit2.HttpException
import timber.log.Timber
class RefreshDataWorker(appContext: Context, params: WorkerParameters) :
CoroutineWorker(appContext, params) {
override suspend fun doWork(): Result {
val database = getDatabase(applicationContext)
val repository = VideosRepository(database)
try {
repository.refreshVideos()
Timber.d("Work request for sync is run")
} catch (e: HttpException) {
return Result.retry()
}
return Result.success()
}
companion object {
/**
* Define a work name to uniquely identify this worker.
*/
const val WORK_NAME = "com.example.android.devbyteviewer.work.RefreshDataWorker"
}
}
CodePudding user response:
I've had the same problem while working with WorkManager.
Pulling meaning from your post and the error message, this is very likely an import related issue. Check your Application dependencies.
Rather than:
implementation "android.arch.work:work-runtime-ktx:$work_version"
Use:
implementation "androidx.work:work-runtime-ktx:$work_version"