Reputation: 3003
According code below:
@Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
@Singleton
@Provides
Context providesContext() {
return application;
}
@Singleton
@Provides
IAppDbHelper providesAppDbHelper() {
// a SQLiteOpenHelper class
return new AppDbHelper(application);
}
}
AppComponent:
@Singleton
@Component(modules = AppModule.class)
public interface AppComponent {
void inject(MainActivity mainActivity);
void inject(SecondActivity secondActivity);
IAppDBHelper providesIAppDBHelper();
}
MainActivity: public class MainActivity extends AppCompatActivity { @Inject IAppDBHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MyApplication)getApplication()).getComponent()
.inject(this);
// It's OK
helper.getWritable().execSQL("XXX");
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
}
SecondActivity:
public class SecondActivity extends AppCompatActivity {
@Inject
IAppDBHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
// nullPointer on helper
helper.getWritable().execSQL("XXX");
}
}
After inject
ing my AppComponent
inside my SecondActivity
, nullPointer
error fixes but my question is do I have to inject
My AppComponent
every time I want inject IAppDbHelper
? So what does @Singleton
and injecting in inside my MainActivity
mean? Doesn't should they inject that IAppDbHelper
for my SecondActivity
?
Upvotes: 0
Views: 367
Reputation: 95774
You will need to get your component and inject each class that Android creates. This typically means all Activities, Fragments, and Views. Dagger can't create those classes, so the only way Dagger knows about the externally-created instance is when you pass it into the inject
method on your Component.
During the injection, all @Inject
fields on MainActivity and SecondActivity will be provided, and any instances that Dagger creates will also have their dependencies injected, and so forth all the way down the line. This means that you won't usually need your Component directly outside of your externally-created classes like Activities and Fragments, or (of course) your Application instance where you create the Component instance itself.
@Singleton
does mean that the instance will remain the same between MainActivity, SecondActivity, and any future instances of MainActivity or SecondActivity that Android may create as you background the app. However, you still need to request injection for those classes as Android creates them, in order to receive that same instance that you've guaranteed with @Singleton
.
Upvotes: 1