Dagger 2 activity injection not working

走远了吗. 提交于 2019-12-05 22:56:05

Well... After the full day spend on this I decide to post it and after 5 minutes I found the solution.

I'm using a BaseActivity for all my activity, and I thought I could use this to inject my components but seams this is not possible.

So I just change this line in my ActivityComponent

public void inject(BaseActivity activity) 

to

public void inject(MainActivity activity) 

So to the name of the activity where I'm injecting the dependencies...

What brings me to a new question. How can I implement a base component to handle all my activities? or I must create a Component for each view/activity/fragment I want to have DI?

@Marcel, I recently migrated a project from Dagger 1.2 over to 2.0. I had similar solution where abstract BaseActivity injected the dependencies by doing something along the lines of "application.inject(this);". With Dagger 2.0 this is not possible (as of now) as mentioned in the comment above.

One of the ways I got around this was by changing the "inject" method in the Application class itself to strong type the object. For Example..

class MyApp extends Application {
   ...
   public void inject(Object activity) {
    if (activity instanceof MainActivity) {
      mComponent.inject((MainActivity) activity);
    } else if (activity instanceof SubActivity) {
      mComponent.inject((SubActivity) activity);
    }
  }
}

With that I did not have to change anything in my existing classes.

FYI: There is a project called Bullet by @thomas-broyer that does this too.

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