Android Dagger 2 suggest change

Component setup for Application and Activity injection

A basic AppComponent that depends on a single AppModule to provide application-wide singleton objects.

@Component(modules = AppModule.class)
public interface AppComponent {

    void inject(App app);

    Context provideContext();

    Gson provideGson();

A module to use together with the AppComponent which will provide its singleton objects, e.g. an instance of Gson to reuse throughout the whole application.

public class AppModule {

    private final Application mApplication;

    public AppModule(Application application) {
        mApplication = application;

    Gson provideGson() {
        return new Gson();

    Context provideContext() {
        return mApplication;

A subclassed application to setup dagger and the singleton component.

public class App extends Application {

    AppComponent mAppComponent;

    public void onCreate() {

        DaggerAppComponent.builder().appModule(new AppModule(this)).build().inject(this);

    public AppComponent getAppComponent() {
        return mAppComponent;

Now an activity scoped component that depends on the AppComponent to gain access to the singleton objects.

@Component(dependencies = AppComponent.class, modules = ActivityModule.class)
public interface MainActivityComponent {

    void inject(MainActivity activity);

And a reusable ActivityModule that will provide basic dependencies, like a FragmentManager

public class ActivityModule {

    private final AppCompatActivity mActivity;

    public ActivityModule(AppCompatActivity activity) {
        mActivity = activity;

    public AppCompatActivity provideActivity() {
        return mActivity;
public FragmentManager provideFragmentManager(AppCompatActivity activity) {
    return activity.getSupportFragmentManager();

Putting everything together we’re set up and can inject our activity and be sure to use the same Gson throughout out app!

public class MainActivity extends AppCompatActivity {

    Gson mGson;

    protected void onCreate(Bundle savedInstanceState) {

                .activityModule(new ActivityModule(this))

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents
64 Menu
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close