My Android app has multiple activities. The MainActivity constructs a Dagger2 component in its onCreate() method and assigns it to a static variable so any class can call the static method MainActivity.getDaggerComponent() to then inject itself with dependencies.
The problem I'm discovering is that when I start up my VideoPlayerActivity, the MainActivity object sometimes gets its onPause() invoked. If this happens, the static component variable gets set to null. At a later point, VideoPlayerActivity needs to inject its dependencies, but there is no component so things blow up.
How does one ensure that a Dagger2 component is available at all times for all activities?
Initialize Dagger component in
Application
class or just statically. It might be that you're doing a very wrong thing trying to use dependencies of one Activity in another Activity. This might create memory leaks and in particular sounds like a design problem. What if your firstActivity
was already destroyed? Who will free up the Dagger instance? Why graph belongs to firstActivity
and not to the second one? What if user will enter your app from the secondActivity
- then first one won't be even initialized. And so on, and so on.If you still need
Activity
instance, then you should useActivity
specific component within theActivity
and move everything else in global (Application
wide) component.