Diaz diaz
Diaz diaz

Reputation: 284

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.

Upvotes: 1

Views: 933

Answers (1)

David Medenjak
David Medenjak

Reputation: 34542

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. e.g. see this answer for reference.

Upvotes: 4

Related Questions