我正在尝试在我的应用程序中实现mvvm设计模式,我已经创建了viewmodel和repository类,但是当我尝试在main活动中示例化viewmodel时,它会在下面显示错误红线 MainActivity
在下面的行中示例化时。 pdfViewModel = new ViewModelProvider(MainActivity.this).get(PdfViewModel.class);
下面是我的代码:
主活动.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;
}
}
以上代码中需要更正什么?
1条答案
按热度按时间d8tt03nd1#
您的代码正在尝试创建该类的新示例
ViewModelProvider
(与new
关键字)而这不是示例化viewmodel的正确方法。在
MainActivity
,而不是:尝试:
注意正确的类是
ViewModelProviders
(结尾有一个“s”),您需要调用static方法of
而不是用new
.为了使您的代码更加清晰,我建议您学习kotlinktx方法
viewModels
,如本文所述。不过,你得用Kotlin。