尝试在null obj ref上调用方法ViewModelFactory

我访问了以下链接,但未找到“有效的”结果:

Cannot create an instance of class ViewModel

Cannot create an instance of ViewModel class (Unable to start activity ComponentInfo)

日志给了我一个运行时异常:

Unable to start activity ComponentInfo{MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method '.ViewModelProvider$Factory.create(java.lang.Class)' on a null object reference

HomeFragment.java

 // Error Line
 homeViewModel =
                ViewModelProviders.of(this, ViewModelFactory).get(HomeViewModel.class);

HomeViewModel.java

public class HomeViewModel extends ViewModel {
    private FirestoreRepository repository;
    private LiveData<List<FirestoreOperations>> listLiveData;

    public HomeViewModel(@NonNull LiveData<List<FirestoreOperations>> application) {
        repository = new FirestoreRepository(application);
        listLiveData = repository.getAllDocs();
    }
    // Code...Code...

ViewModelFactory

package com.example.android.predictious.ui.home;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;

import java.util.List;

public class ViewModelFactory implements ViewModelProvider.Factory {

    private final LiveData<List<FirestoreOperations>> mListLiveData;

    public ViewModelFactory(LiveData<List<FirestoreOperations>> mListLiveData) {
        this.mListLiveData = mListLiveData;
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass.isAssignableFrom(HomeViewModel.class)) {
            return (T) new HomeViewModel(mListLiveData);
        }
        //noinspection unchecked
        throw new IllegalArgumentException("Unknown ViewModel class");
    }
    public <T extends ViewModel> T get(Fragment fragment, Class<T> modelClass) {
        if (modelClass.getAnnotation(SharedViewModel.class) == null) {
            return ViewModelProviders.of(fragment, this).get(modelClass);
        } else {
            return get(fragment, modelClass);
        }
    }
}

SharedViewModel.java

package com.example.android.predictious.ui.home;

import androidx.fragment.app.Fragment; // NOPMD
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface SharedViewModel {}

如果没有针对我的问题的Android代码,是否应该使用Dagger解决此问题?

评论