我想将MyRepository
对象直接注入我的ViewModel
类中,但是我总是得到一个NullPointerException
。这就是我尝试过的。
这是我的AppModule
班:
@Module
public class AppModule {
@Singleton
@Provides
static Retrofit provideRetrofitInstance(){
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
@Provides
static MyApi provideMyApi(Retrofit retrofit){
return retrofit.create(MyApi.class);
}
@Provides
static MyRepository provideMyRepository(MyApi myApi) {
return new MyRepository(myApi);
}
}
这是我要注入的课程:
@Singleton
public class MyViewModel extends AndroidViewModel {
@Inject MyRepository myRepository; //Is not injected!!!
LiveData<Data> myLiveData;
MyViewModel(Application application, City city) {
super(application);
myLiveData = myRepository.addDataToLiveData(city);
}
LiveData<Data> getLiveData() {
return myLiveData;
}
}
这是我的存储库类:
public class MyRepository {
private MyApi myApi;
public MyRepository(MyApi myApi) {
this.myApi = myApi;
}
LiveData<Data> addDataToLiveData(City city) {
//Make api call
}
}
答案 0 :(得分:0)
使您的存储库构造函数可注入
public class MyRepository {
private MyApi myApi;
@Inject
public MyRepository(MyApi myApi) {
this.myApi = myApi;
}
LiveData<Data> addDataToLiveData(City city) {
//Make api call
} }
并从模块
中删除此存储库提供程序 @Provides
static MyRepository provideMyRepository(MyApi myApi) {
return new MyRepository(myApi);
}
应用模块
@Module
public class AppModule {
@Singleton
@Provides
static Retrofit provideRetrofitInstance(){
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
@Provides
static MyApi provideMyApi(Retrofit retrofit){
return retrofit.create(MyApi.class);
}
}
并从viewModel中删除Singleton批注
public class MyViewModel extends AndroidViewModel {
@Inject MyRepository myRepository; //Is not injected!!!
LiveData<Data> myLiveData;
MyViewModel(Application application, City city) {
super(application);
myLiveData = myRepository.addDataToLiveData(city);
}
LiveData<Data> getLiveData() {
return myLiveData;
}
}