I try to inject the repository into my ViewModel using Dagger 2 similar with Architecture Guide. However, my repository value is always null.
Here is my ViewModel
public class MainActivityViewModel extends ViewModel {
@Inject
public CustomRepository repository;
private MutableLiveData<List<CustomItem>> items = new MutableLiveData<>();
public void initModel(Date month){
try {
items = repository.getItems(month);
} catch (Exception e) {
items = new MutableLiveData<>();
}
}
public MutableLiveData<List<CustomItem>> getItems() {
return items;
}
}
My AppModule
@Module
public class AppModule {
Application mApplication;
public AppModule(Application application) {
mApplication = application;
}
@Provides
@Singleton
Application providesApplication() {
return mApplication;
}
@Provides
@Singleton
public ItemDao provideItemDao(AppDatabase appDatabase){
return appDatabase.itemDao();
}
@Provides
@Singleton
public AppDatabase provideDatabase(){
//TODO remove allow main thread and use asynchronous query
return Room.databaseBuilder(mApplication, AppDatabase.class, AppDatabase.DB_NAME)
.allowMainThreadQueries().build();
}
}
My AppComponent
@Singleton
@Component(modules = {AppModule.class})
public interface MyAppComponent {
public CustomRepository repository();
}
My Application class
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
DaggerMyAppComponent.builder()
.appModule(new AppModule(this))
.build();
}
}
Could you please help me to show what I'm missing here? I guess that I need to call inject() method somewhere but I'm not really sure how and where I should do this.