1

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.

Sachin Varma
  • 2,175
  • 4
  • 28
  • 39
Diaz diaz
  • 284
  • 1
  • 7
  • 21

1 Answers1

4

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.

David Medenjak
  • 33,993
  • 14
  • 106
  • 134
  • Thx for answer David . That's a great one . So what i understood that i have to create multiple inject methods if i need a field injection in multiple Activities and Fragments ? Am i wrong here ? – Diaz diaz Jun 01 '18 at 12:49
  • Its a Coincident My last 4 questions are only answered by the developers from Austria in recent 3 days. Thx – Diaz diaz Jun 01 '18 at 12:57