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?
When use
void inject(MainActivity context);
its working fine. Why ?If i need to inject
RetroFit
in Multiple classes what should be the approach. Creatinginject()
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.