8

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?

AndroidDev
  • 5,193
  • 5
  • 37
  • 68
  • AFAIK you cannot inject context directly with that annotation. That is reserved for modules. – m0skit0 Feb 16 '21 at 13:45
  • 1
    Please check the example at https://developer.android.com/training/dependency-injection/hilt-android#java public class AnalyticsServiceImpl implements AnalyticsService { private final Context context; @Inject AnalyticsAdapter(@ApplicationContext Context context) { this.context = context; } } So do we still need a provideContext method? – AndroidDev Feb 16 '21 at 13:48
  • Have you created a module to provide CardLayoutManager with a scope (ie. SingletonScope)? If yes please share the code – Naresh NK May 31 '21 at 08:46
  • @AndroidDev Have you found a solution yet? This is driving me insane – Emmanuel Conradie Aug 18 '21 at 19:28

2 Answers2

12

You need to annotate the constructor properly:

class CardLayoutManager @Inject constructor(@ApplicationContext val context: Context) {
}
Cristian Holdunu
  • 1,880
  • 1
  • 18
  • 43
  • That was a Java class. Even in Kotlin files I'm getting the same error with constructor injection. – AndroidDev Feb 16 '21 at 16:53
  • From what I know, wherever you use the Hilt Components, you need your entry class to be annotated with `@AndroidEntryPoint` in order to load the dependencies graph. Is this your case? – Cristian Holdunu Feb 17 '21 at 14:52
  • Make sure you remember to include the `val` keyword! I forgot to include it, and once I added it like in your answer my issue was resolved. – grizzasd Jan 28 '22 at 21:13
0

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.

Emmanuel Conradie
  • 345
  • 1
  • 5
  • 20