java - 无法在 Android 中实例化 ViewModel
问题描述
我正在尝试在我的应用程序中实现 MVVM 设计模式。我已经创建了视图模型和存储库类,但是当我尝试在 MainActivity 中实例化视图模型时,它MainActivity
在下面的行中实例化时在下面显示错误红线。
pdfViewModel = new ViewModelProvider(MainActivity.this).get(PdfViewModel.class);
下面是我的代码:
MainActivity.java
public class MainActivity extends AppCompatActivity {
PdfViewModel pdfViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pdfViewModel = new ViewModelProvider(MainActivity.this).get(PdfViewModel.class);
}
}
PdfViewModel.java
public class PdfViewModel extends AndroidViewModel {
private PdfRepository pdfRepository;
public PdfViewModel(@NonNull Application application) {
super(application);
pdfRepository = new PdfRepository(application);
}
public LiveData<List<Pdfs>> getAllPdfs(){
return pdfRepository.getMutableLiveData();
}
}
PdfRepository.java
public class PdfRepository {
private ArrayList<Pdfs> list = new ArrayList<>();
private MutableLiveData<List<Pdfs>> mutableLiveData = new MutableLiveData<>();
private Application application;
public PdfRepository(Application application){
this.application = application;
}
public MutableLiveData<List<Pdfs>> getMutableLiveData(){
SharedPreferences preferences = application.getSharedPreferences("Credentials", Context.MODE_PRIVATE);
String email = preferences.getString("email",null);
Retrofit retrofit = RetrofitClient.getInstance();
ApiService apiService = retrofit.create(ApiService.class);
Call<List<Pdfs>> call = apiService.getFiles(email);
call.enqueue(new Callback<List<Pdfs>>() {
@Override
public void onResponse(Call<List<Pdfs>> call, Response<List<Pdfs>> response) {
if(response.body() != null){
list = (ArrayList<Pdfs>) response.body();
mutableLiveData.setValue(list);
}
}
@Override
public void onFailure(Call<List<Pdfs>> call, Throwable t) {
TastyToast.makeText(application,t.getMessage(),TastyToast.LENGTH_SHORT,TastyToast.ERROR).show();
}
});
return mutableLiveData;
}
}
上面的代码中需要更正什么?
解决方案
您的代码正在尝试创建类的新实例ViewModelProvider
(使用new
关键字),这不是实例化 ViewModel 的正确方法。
上MainActivity
,而不是:
pdfViewModel = new ViewModelProvider(MainActivity.this).get(PdfViewModel.class);
尝试:
pdfViewModel = ViewModelProviders.of(this).get(PdfViewModel.class);
请注意,正确的类是ViewModelProviders
(末尾带有“s”),您需要调用静态方法of
,而不是使用new
. 如果您无法导入该类,请确保已将依赖项 'androidx.lifecycle:lifecycle-extensions:2.2.0' 添加到app/build.gradle
.
为了使您的代码更加清晰,我建议您了解 Kotlin KTX 方法viewModels
,如此处所述。不过,您需要使用 Kotlin。
推荐阅读
- html - 固定宽度内的全宽容器,没有页面 x-scrollbar
- kubernetes - 两个不同网格之间的 gRPC 连接被重置
- python - 如何从 Python 中的列中提取小时和小步舞曲,例如 0 Days 09:30:15
- python - Pandas df比较两个日期条件
- kubernetes - Jenkins Kubernetes 构建因禁止而失败(用户 = 系统:匿名,动词 = 获取,资源 = 节点,子资源 = 代理)
- capacitor - 使用 Capacitor Filesystem API 获取系统文件路径
- swift - let NAME1 = NAME2( params ) { var1, var2 在 Swift 中是什么意思?
- r - 如何在图中制作包含两个因子变量和 % 的饼图
- java - 我在尝试从其他方法访问此返回的 resultSetCustomer. 时收到错误“java.sql.SQLException:结果集结束后”
- powerbi - 部门和地理粒度问题