AndroidDev
AndroidDev

Reputation: 5555

How to provide Context with Hilt Android?

I am trying to migrate a project to Hilt but facing the below issue, not sure how to pass Context with Hilt. If I remove provideContext method then it complains with the below error:

error: [Dagger/MissingBinding] @dagger.hilt.android.qualifiers.ApplicationContext android.content.Context cannot be provided without an @Provides-annotated method.

But my understanding is that in Hilt we don't need provideContext method and we could just use @ApplicationContext like below:

@Inject
public CardLayoutManager(@ApplicationContext Context context) {
    mContext = context;
}

Am I missing something?

Upvotes: 9

Views: 12004

Answers (2)

Emmanuel Conradie
Emmanuel Conradie

Reputation: 435

Remove the @ApplicationContext annotation

I have read all the documentation more than 5 times, tried the correct method and updated all the Hilt libraries but the problem prevailed.

Once I removed the annotation it all worked perfectly which is strange because I used the correct approach (using the @ApplicationContext annotation) in my other projects.

Upvotes: 0

Cristian Holdunu
Cristian Holdunu

Reputation: 1918

You need to annotate the constructor properly:

class CardLayoutManager @Inject constructor(@ApplicationContext val context: Context) {
}

Upvotes: 12

Related Questions