android - 如何将 Retrofit 对象直接注入到存储库类中?
问题描述
我想将一个Retrofit
对象直接注入我的MyRepository
班级,但我总是得到一个NullPointerException
. 这是我尝试过的。
这是我的AppModule
课:
@Module
public class AppModule {
@Singleton
@Provides
static Retrofit provideRetrofitInstance(){
return new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
这是我的视图模型类:
public class MyViewModel extends AndroidViewModel {
LiveData<Data> myLiveData;
MyViewModel(Application application, City city) {
super(application);
myLiveData = myRepository.addDataToLiveData(city);
}
LiveData<Data> getLiveData() {
return myLiveData;
}
}
这是我要注入 Retofit 的存储库类:
public class MyRepository {
private String myTex;
@Inject
private Retrofit retrofit;
public MyRepository(String myText) {
this.myText = myText;
}
LiveData<Data> addDataToLiveData(City city) {
//Make api call using retrofit
}
}
编辑:
这就是我ViewModel
在我的活动类中实例化我的方式:
MyRepository repository = new MyRepository("MyText");
Application application = activity.getApplication();
MyViewModelFactory factory = new MyViewModelFactory(application, repository);
MyViewModel viewModel = ViewModelProviders.of(this, factory).get(MyViewModel.class);
解决方案
使您的存储库可注入是最简单的解决方案,它还允许您将它注入到使用它的位置,在您ViewModel
的 s 或Interactor
s 中:
@Singleton
public class MyRepository {
private Retrofit retrofit;
@Inject
public MyRepository(Retrofit retrofit) {
this.retrofit = retrofit;
}
LiveData<Data> addDataToLiveData(City city) {
//Make api call using retrofit
}
}
编辑:您可以通过 Dagger 提供文本并将其注入您的构造函数中,就像这样
@Inject
public MyRepository(String myText, Retrofit retrofit)
请注意,您需要使用@Named
or@Qualifier
作为您的字符串。
或者,您可以注入您的存储库调用inject(this)
,语法取决于您如何设置 Dagger
somehowGetDaggerComponent().inject(this)
我强烈建议您使用第一种解决方案。
推荐阅读
- python - 在直线/常数之间的曲线上找到两个点/导数
- ssh - gnome-terminal 和多个 ssh 到不同的计算机
- bash - 使用 rsync 比较两个文件夹并复制所有新的和更改的内容
- python-3.x - 用户输入后打印带有项目符号的列表(聊天机器人问题)
- javascript - 如何在纯 Javascript webapp 中使用经过训练的 TensorFlow 模型
- c# - 在 Docker 容器中运行时 Swagger 未打开
- python-3.x - 在连接电机的 Raspberry PI 上使用 Python 进行多线程/多处理
- wordpress - wordpress 上的 HTTPS 通过 http 提供资产
- json - 如何将简单的 JSON 转换为 DynamoDB JSON?
- azure-devops - 在服务器配置向导中将 TFS 升级到 AzureDevops 2019 时 SSH 设置的目的是什么?