Dagger2 and in one of the articles I found this class

 public class App extends Application { private static AppComponent component; public static AppComponent getComponent() { return component; } @Override public void onCreate() { super.onCreate(); component = buildComponent(); } protected AppComponent buildComponent() { return DaggerAppComponent.builder() .anotherModule(new AnotherModule()) .modelModule(new ModelModule()) .build(); } } 

Which is convenient to use for initialization, but the fact is that the onCreate() method is not called and accordingly I get null when I call the App.getComponent().inject(this);

At first I took and just did this:

 public class App extends Application { public static AppComponent getComponent() { return DaggerAppComponent.builder() .anotherModule(new AnotherModule()) .modelModule(new ModelModule()) .build(); } } 

But then I thought that if it was done that way, then why did it do that))

  1. But then why doesn't onCreate() ?
  2. and the second question is why not to do it in my second example?
  • Do you think that every time you ask for a component, you should build it again? Those. the entire dependency tree will be recreated. And in onCreate create a component to get a link to the application context. Try DBHelper to create without context ... - Yura Ivanov

1 answer 1

The onCreate() method of your App class is not called because the App class is not used anywhere.

To use the App class (instead of the standard Application ), in AndroidManifest.xml it is necessary to add an attribute to the application tag:

 android:name=".App" 

thereby explicitly indicating that the base class of your application is the App class you created (and not the Application class, which is considered the base class by default ).

  • And if I don’t need the app class to be a base class? My base class is MainActivity ... Then make this method static as I described will be correct? - Aleksey Timoshchenko
  • @AlekseyTimoshchenko, You now have an application base class - the Application class, do not confuse Activity and Application , these are two different classes. - post_zeew
  • aa understood, I didn't even think about it before .. We just expand the standard Application class and add initialization to it already ... But in order for it to be accepted, you need to specify it in the manifest, its name, did I understand that correctly? - Aleksey Timoshchenko
  • @AlekseyTimoshchenko, Yes, that's right. - post_zeew
  • And if you understand dagger, you can help here.stackoverflow.com/questions/587234/… - Aleksey Timoshchenko