8

As per documentation for Hilt, I completed all the steps

Add Class Path to Project Module

classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"

Add Plugins

plugins {
    id "kotlin-kapt"
    id("dagger.hilt.android.plugin")
}

Add Dependencies

dependencies {
    implementation("com.google.dagger:hilt-android:$hilt_version")
    kapt("com.google.dagger:hilt-android-compiler:$hilt_version")
}

Annotated Application Class, in my case AppClass, with @HiltAndroidApp. Annotated Activity and regarding fragment with @AndroidEntryPoint.

Created Module as

@InstallIn(AppClass::class)
@Module
object DatabaseModule {

    @Provides
    @Singleton
    fun provideAppDB(application: Application): AppDB {
        return AppDB.getDatabase(application)
    }

    @Provides
    @Singleton
    fun provideMediaDao(appDB: AppDB): MediaDao {
        return appDB.downloadMediaDao()
    }
}

Injected it in ViewModel class as

@HiltViewModel
class DownloadViewModel @Inject constructor(
    private val mediaDao: MediaDao
): ViewModel() {
    ...
}

But After following all the steps I got the error saying "@InstallIn, can only be used with @DefineComponent-annotated classes, but found: [com.abc.xyz.AppClass]"

2 Answers 2

24

As defined in the Codelab, I replaced this

@InstallIn(AppClass::class)

with this

@InstallIn(SingletonComponent::class)

And it's working.

1
  • 3
    But why? Maybe more explanation would be useful?
    – MeLean
    Commented Jun 27, 2022 at 20:14
6

In my case, I made a career-ending error and I was duly punished by spending the whole day stuck on a simple typo!

Instead of using SingletonComponent::class I misspelt it as Singleton::class

//worst error of my career
@Module
@InstallIn(Singleton::class)
object AppModule { ... }

I changed to SingletonComponent::class and bypassed the error.

//changed it to this
@Module
@InstallIn(SingletonComponent::class)
object AppModule { ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.