首页 > 解决方案 > 无法在 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;
}

}

上面的代码中需要更正什么?

标签: javaandroidmvvmandroid-livedataandroid-viewmodel

解决方案


您的代码正在尝试创建类的新实例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。


推荐阅读