Move inject before onCreate for Activity
See original GitHub issueDaggerAppCompatActivity.onCreate() currently looks like this:
super.onCreate(var1);
AndroidInjection.inject(this);
This causes a NullPointerException when a Fragment is added via the support FragmentManager and a configuration change occurs (e.g. screen rotation), and the Fragment is restored by the framework. The problem is that Fragment.onAttach() is then called within the Activity’s onCreate(), where fields are not yet injected, but needed to inject the Fragment.
Instead, the order of the two statements needs to be flipped - injection needs to happen before super.onCreate().
I’ve created a sample app to demonstrate the issue: https://github.com/bubenheimer/daggerinitorderbug The sample app uses my own builds of the Dagger artifacts, to work around other issues with RC1.
I don’t know the behavior with framework Activities, as opposed to AppCompatActivities. I’d think it should be treated the same, at least to be consistent, but have not tested it.
I don’t have a strong opinion on the order for DaggerFragment - the equivalent problem does not occur for support child Fragments (children of a parent Fragment) - also shown in my sample app. Injecting after ‘super.onAttach()’ works fine in all of my production code, too, but perhaps it would be better to flip the order to be consistent.
Seeing this issue in the code was what led me to spend my time on evaluating the RC, to get it changed before reaching release. Thanks for providing an RC!
Issue Analytics
- State:
- Created 7 years ago
- Reactions:11
- Comments:13
Top GitHub Comments
Thank you, @bubenheimer!
I’ve tried to integrate the compiled artifacts from your repo and it works like a charm even with Kotlin. In fact, this is the only workable solution I’ve found so far which makes it possible to play with the new Android Injection feature.
I’m injecting it into the constructor of the presenter which manages all permissions related logic.