【问题标题】:Hilt - Field injection returning a null object referneceHilt - 字段注入返回一个空对象引用
【发布时间】:2021-06-28 01:22:13
【问题描述】:

这是我第一次将Hilt 用于 DI,我不确定自己做错了什么。我正在尝试将Field inject 我的TestClass 转换为我的MainActivity,但是当我调用注入的TestClass 的方法时,它给了我一个空对象引用

我确保创建了一个 BaseApplication 类,该类具有注释 HiltAndroidApp

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

我试图注入我的MainActivity的类

import javax.inject.Inject;

public class TestClass {

    @Inject
    public TestClass() {
    }

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

在我的MainActivity 中使用FieldInjection

@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
    
        ...

我遵循了 YouTube 上的一个教程,该教程正在执行 Field Injection。不知道我在这里做错了什么。

【问题讨论】:

  • 我很笨,只加了implementation 'com.google.dagger:hilt-android:2.37'。我还需要添加annotationProcessor 'com.google.dagger:hilt-compiler:2.37'classpath 'com.google.dagger:hilt-android-gradle-plugin:2.37'apply plugin: 'dagger.hilt.android.plugin'
  • 很高兴您解决了问题!如果有机会,请将您的评论以self-answer 的形式复制到答案框中(除了“我很愚蠢”;您不是),并在几天后接受。这将您的问题标记为已解决,允许其他人找到并支持它,并允许未来的读者编辑或更新您的答案。

标签: android dagger-2 dagger-hilt


【解决方案1】:

我只在需要添加时在依赖项中添加了implementation 'com.google.dagger:hilt-android:2.37'

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

【讨论】:

    猜你喜欢
    • 2021-07-13
    • 2021-05-18
    • 2019-09-05
    • 2016-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 2021-03-31
    相关资源
    最近更新 更多