6

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.

Minh Khoi
  • 115
  • 2
  • 12
  • Yes, you're not injecting the ViewModel, but there is no need to manually inject everything. Just yesterday I explained how to use Constructor Injection, please have a look here: https://stackoverflow.com/a/46304549/1837367 – David Medenjak Sep 20 '17 at 12:23
  • Please take a look at https://stackoverflow.com/a/49087002/4770877 – yoAlex5 Dec 30 '19 at 11:10

0 Answers0