1

This is my first time using Hilt for DI and I'm unsure what I'm doing incorrectly. I'm trying to Field inject my TestClass into my MainActivity, but it's giving me a null object reference when I call the method of the injected TestClass

I've made sure to create an BaseApplication class that has the annotation HiltAndroidApp

@HiltAndroidApp
public class BaseApplication extends Application {
  ...
}

The class I'm trying to inject into my MainActivity

import javax.inject.Inject;

public class TestClass {

    @Inject
    public TestClass() {
    }

    public String getName(){
        return "Hello World";
    }
}

And using FieldInjection in my MainActivity:

@AndroidEntryPoint
public class MainActivity extends AppCompatActivity implements TestAdapterCallback {

    @Inject
    TestClass testClass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        Timber.d(testClass.getName()); //Giving a null object reference
    
        ...

I followed a tutorial off youtube that is doing Field Injection. Not sure what I'm doing incorrectly here.

enter image description here

DIRTY DAVE
  • 2,523
  • 2
  • 20
  • 83
  • I'm stupid and only added ```implementation 'com.google.dagger:hilt-android:2.37'``` . I needed to also add ```annotationProcessor 'com.google.dagger:hilt-compiler:2.37'```, ```classpath 'com.google.dagger:hilt-android-gradle-plugin:2.37'```, and ```apply plugin: 'dagger.hilt.android.plugin'```. – DIRTY DAVE Jun 28 '21 at 02:06
  • 2
    I'm glad you've solved your problem! When you get a chance, please copy your comment into the answer box as a [self-answer](https://stackoverflow.com/help/self-answer) (aside from the "I'm stupid"; you're not) and accept it a couple of days later. That marks your problem as solved, allows others to find and upvote it, and allows future readers to edit or update your answer. – Jeff Bowman Jul 01 '21 at 20:26

1 Answers1

3

I only added implementation 'com.google.dagger:hilt-android:2.37' in my dependencies when I needed to also add

apply plugin: 'com.android.application'
apply plugin: 'dagger.hilt.android.plugin'

...

dependencies {
    implementation 'com.google.dagger:hilt-android:2.37
    annotationProcessor 'com.google.dagger:hilt-compiler:2.37'
}

buildscript {
    repositories {
        google()
        jcenter()
        
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.3'

        classpath 'com.google.dagger:hilt-android-gradle-plugin:2.37'
    }
}
DIRTY DAVE
  • 2,523
  • 2
  • 20
  • 83