question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Hilt Worker Inject throws NoSuchMethodException

See original GitHub issue

Currently using com.google.dagger:hilt-android:2.37, compiler is com.google.dagger:hilt-android-compiler:2.37, noticing issue after upgrading from 2.33. This error occurs when a repository or another dependency injected component, is injected into the worker, it works fine without the repository injected. This previously worked on v2.33 and I don’t see any breaking changes in the changelog.

Error message:

E/WM-WorkerFactory: Could not instantiate com.testapp.TestApp.services.workers.TestWorker
    java.lang.NoSuchMethodException: com.testapp.TestApp.services.workers.TestWorker.<init> [class android.content.Context, class androidx.work.WorkerParameters]
        at java.lang.Class.getConstructor0(Class.java:2332)
        at java.lang.Class.getDeclaredConstructor(Class.java:2170)
        at androidx.work.WorkerFactory.createWorkerWithDefaultFallback(WorkerFactory.java:95)
        at androidx.work.impl.WorkerWrapper.runWorker(WorkerWrapper.java:244)
        at androidx.work.impl.WorkerWrapper.run(WorkerWrapper.java:136)
        at androidx.work.impl.utils.SerialExecutor$Task.run(SerialExecutor.java:91)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:923)
2021-06-14 20:04:16.894 5119-5335/com.testapp.TestApp E/WM-WorkerWrapper: Could not create Worker com.testapp.TestApp.services.workers.TestWorker

Worker code example:

@HiltWorker
class TestWorker @AssistedInject constructor(
    @Assisted appContext: Context,
    @Assisted workerParams: WorkerParameters,
    val repository: TestRepository
) : CoroutineWorker(appContext, workerParams) {

    override suspend fun doWork(): Result = withContext(Dispatchers.IO){
        // Indicate whether the work finished successfully with the Result
        return@withContext try{
            Result.success()
        } catch (e: Exception) {
            Result.retry()
        }
    }

Default initializer removed

<provider
            android:name="androidx.startup.InitializationProvider"
            android:authorities="${applicationId}.androidx-startup"
            android:exported="false"
            tools:node="merge">
            <!-- If you are using androidx.startup to initialize other components -->
            <meta-data
                android:name="androidx.work.impl.WorkManagerInitializer"
                android:value="androidx.startup"
                tools:node="remove" />
        </provider>

Application file

@HiltAndroidApp
class App : Application(), Configuration.Provider {

    @Inject
    lateinit var workerFactory: HiltWorkerFactory

    /**
     * Work Manager Configuration
     */
    override fun getWorkManagerConfiguration(): Configuration {
        return Configuration.Builder()
            .setWorkerFactory(workerFactory)
            .setMinimumLoggingLevel(android.util.Log.DEBUG)
            .build()
    }
}

Repository injection

@Module
@InstallIn(SingletonComponent::class)
object RepositoryModule {

    @Provides
    @Singleton
    fun provideTestRepository(
        testDao: TestDao,
        api: Api,
        appExecutors: AppExecutors
    ): TestRepository {
        return TestRepository(testDao, api, appExecutors)
    }
}

Viewmodel code to call worker request

val workRequest = PeriodicWorkRequestBuilder<TestWorker>(15, TimeUnit.MINUTES)
                            .setInitialDelay(1, TimeUnit.MINUTES)
                            .setConstraints(constraints)
                            .build()

                        WorkManager.getInstance(requireContext()).enqueueUniquePeriodicWork(Constants.Worker.WORKER, ExistingPeriodicWorkPolicy.REPLACE, workRequest )

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
danysantiagocommented, Jun 17, 2021

Ah - I think this is a bit lost in the release notes, but WorkManagerInitializer got moved in alpha02 and onward, and based on the code that you have you are still removing the one in the outdated package, androidx.work.impl.WorkManagerInitializer vs androidx.work.WorkManagerInitializer.

The full code to only remove WorkManager’s initializer (without disabling all of androidx.startup) should be:

<provider
    android:name="androidx.startup.InitializationProvider"
    android:authorities=\"${applicationId}.androidx-startup"
    android:exported="false"
    tools:node="merge">
    <!-- If you are using androidx.startup to initialize other components -->
    <meta-data
        android:name="androidx.work.WorkManagerInitializer"
        android:value="androidx.startup"
        tools:node="remove" />
 </provider>
1reaction
vincent-paingcommented, Apr 24, 2022

I’m on work manager 2.7.1 and hilt 2.41. Seeing this issue. The only workaround is to create own factory. Seems like workerFactories is empty list in WorkerFactoryModule.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Hilt throws NoSuchMethodException when injecting a worker
Error log: java.lang.NoSuchMethodException: dev.aungkyawpaing.hiltnosuchmethod.ExampleWorker. [class android.content.
Read more >
Hilt and WorkManager error : java.lang ...
Hilt and WorkManager error : java.lang.NoSuchMethodException:<init> [class android.content.Context, class androidx.work.WorkerParameters].
Read more >
Android WorkManager Worker can not be injected using ...
Android WorkManager Worker can not be injected using Dagger Hilt `@WorkerInject`. 2. Hotlists (5)
Read more >
Customizing WorkManager — fundamentals | by Pietro Maggi
Use Dagger to inject parameters in our WorkerFactory; On-Demand initialization ... method an exception (added in v1.0.0) will be thrown.
Read more >
Customize WorkManager with AppStartup & Hilt - Droidcon
In this article, we will learn about WorkManager best practices including performant component initialization with the App Startup library.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found