简体   繁体   中英

Dagger2 Component inject for multiple Activities

This seems very basic question for Dagger2 users . I have recently started exploring it with RetroFit . I have followed some tutorials and came up with the code below(some of it).

    @Singleton
    @Component(modules = {AppModule.class, ApiModule.class})
     public interface ApiComponent {
    void inject(MainActivity context);
     }


    public class MyApplication extends Application {
    private ApiComponent mApiComponent;
    @Override
    public void onCreate() {
        super.onCreate();
        mApiComponent = DaggerApiComponent.builder()
                .appModule(new AppModule(this))
                .apiModule(new ApiModule("https://rect.otp/demos/"))
                .build();
    }
    public ApiComponent getNetComponent() {
        return mApiComponent;
    }
   }

And MainActivity.java

public class MainActivity extends AppCompatActivity {
@Inject
Retrofit retrofit;
ActivityMainBinding mainBinding;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
    ((MyApplication) getApplication()).getNetComponent().inject(this);
    ApiCall api = retrofit.create(ApiCall.class);
}
}

Questions
1. When i change void inject(MainActivity context); to void inject(Context context); i am getting a NullPointerException on retrofit in MainActivity .Why?

  1. When use void inject(MainActivity context); its working fine. Why ?

  2. If i need to inject RetroFit in Multiple classes what should be the approach. Creating inject() for each class is not seems the solution.

I am a newbie to dependency Injections. So Can i have some guidence on it . What will be the proper approach to use it in multiple classes.

When you declare void inject(Context context) Dagger will generate code to inject Context . Since Context does not declare any @Inject annotated fields it will end up injecting nothing. This is why your retrofit is null after the injection.

When you declare void inject(MainActivity context) it will generate code to inject MainActivity that will also set your retrofit , thus it will be initialized.

Dagger will inject parent fields, but not childrens. The class that you declare is the one that the code will be generated for.

Your default way to inject objects should be Constructor Injection where you don't have to manually declare methods or inject the objects. eg see this answer for reference .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM