Skip to content

Move inject before onCreate for Activity #598

Closed
@bubenheimer

Description

DaggerAppCompatActivity.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!

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions