Android Dagger 2 Dependency not being injected

左心房为你撑大大i 提交于 2019-12-05 12:30:19

david.mihola's comment is correct: in order to be able to have @Inject fields initialized, you need to have a method (typically void inject(MyClass)) in your component.

It's worth noting (not specifically for your question, but it could come up) that if you have a base class:

public class BaseActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((AndroidApplication) getApplication()).component().inject(this);
    }
} 

and in your component:

void inject(BaseActivity);

Injecting into a subclass that has it's own @Inject fields won't work:

public class ActualActivity extends BaseActivity {
    @Inject IDependenceyRepository repo;
}

This is because Dagger needs to know the concrete classes that will be injected at compile time, not runtime (like Dagger 1 could do).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!