Reputation: 4127
Started introducing Dagger into my App and I'm having problems getting a very basic field initialized. Here's a reduced version of my code:
@Inject public DaggerUtils daggerUtils;
public class AppState extends Application {
@Override
public void onCreate() {
super.onCreate();
// Set up Dagger
AppModule appModule = new AppModule();
mObjectGraph.create(appModule);
daggerUtils.print();
}
}
Module used:
@Module(
injects = { AppState.class}
)
public class AppModule {
// This provides method is commented out because from what I can understand from the Dagger documentation
// Dagger should automatically take care of calling the constructor I have provided
// with the @Inject annotation. I have tried commenting this out as well and it still
// fails.
//@Provides
//DaggerUtils provideDaggerUtils() {
// return new DaggerUtils();
//}
}
Basic util class:
public class DaggerUtils {
@Inject
public DaggerUtils() {
}
public void print(){
Logger.e("Dagger", "printed instantiated");
}
}
So from what I understand because I have the @Inject annotation before the DaggerUtils constructor and the @Inject annotation before the DaggerUtils instance I'm using in my AppState class, Dagger should take care of initializing the DaggerUtils instance without me having to call the constructor. However it keeps giving me an NullPointerException when I try to call daggerUtils.print() (Line 12 in AppState class). Why is dagger not initializing DaggerUtils? I feel like I'm missing something very basic here. I've also tried using the @Provides method commented out in the AppModule to provide an instantiated DaggerUtils but it still isn't working.
Upvotes: 1
Views: 1726
Reputation: 993
I had same problem this evening.
For every class, who needs injection you must call:
mObjectGraph.create(appModule).inject(this);
That is usefull to create inject method in Application.
public void inject(Object object) {
mObjectGraph.inject(object);
}
Upvotes: 2