Search code examples
androiddagger-2dagger-hilt

Hilt - Field injection returning a null object refernece


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


Solution

  • 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'
        }
    }