I'm trying to inject an instance of CacheManager
into GetTodoRepository
which Dagger is probably successfull with doing since I'm not getting any dagger related errors. But when using cacheManager
in GetTodoRepository
I get a NullPointerException
public class GetTodoRepository {
@Inject
public CacheManager cacheManager;
public RetrofitService retrofitService;
private ResultListener listener;
public GetTodoRepository(@NonNull ResultListener listener) {
this.retrofitService = new RetrofitService();
this.listener = listener;
}
}
@Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
@Provides
@Singleton
public Context providesApplicationContext() {
return application.getApplicationContext();
}
@Provides
@Singleton
public CacheManager provideCacheManager(Context Context) {
return new CacheManager(Context);
}
}
@Singleton
@Component(modules = AppModule.class)
public interface TodoComponents {
void inject(MainViewModel mainViewModel);
void inject(CacheManager cacheManager);
void inject(GetTodoRepository getTodoRepository);
void inject(PostTodoRepository postTodoRepository);
}
1) Setup Dagger (Component) in Application class
public class TodoApplication extends Application {
private static AppComponent components;
@Override
public void onCreate() {
super.onCreate();
components = DaggerAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
public static AppComponent getAppComponent() {
return components;
}
}
2) Call the Component
object from Application
class in the injection target class
public GetTodoRepository(@NonNull ResultListener listener) {
this.listener = listener;
TodoApplication.getAppComponent().inject(this);
}