Search code examples
androidmvvmandroid-livedataandroid-viewmodel

Unable to create instance of view model class in fragment


I am using MVVM approach to create application. I have two fragments in which I am getting data from the server. I have created viewmodel class and repository class in which I am getting data from the server. But the problem is I am unable to create instance of viewmodel class in fragment. It is showing error in this line:

viewModel = new ViewModelProvider(getActivity()).get(FactsViewModel.class);

Below is my code:

MyRepository.class

public class MyRepository {

MutableLiveData<List<Facts>> mutableLiveData = new MutableLiveData<>();
Application application;

public MyRepository(Application application) {
    this.application = application;
}

public MutableLiveData<List<Facts>> getMutableLiveData(){

    Retrofit retrofit = RetrofitClient.getInstance();
    ApiService apiService = retrofit.create(ApiService.class);

    apiService.getFacts().subscribeOn(Schedulers.io())
                         .observeOn(AndroidSchedulers.mainThread())
                         .subscribe(new Observer<List<Facts>>() {
                             @Override
                             public void onSubscribe(Disposable d) {

                             }

                             @Override
                             public void onNext(List<Facts> facts) {

                                 if(facts.size() > 0 && facts != null){

                                     mutableLiveData.setValue(facts);
                                 }
                             }

                             @Override
                             public void onError(Throwable e) {

                                 TastyToast.makeText(application,e.getMessage(),TastyToast.LENGTH_SHORT,
                                         TastyToast.ERROR).show();
                             }

                             @Override
                             public void onComplete() {

                             }
                         });

       return mutableLiveData;
   }
}

FactsViewModel.class

public class FactsViewModel extends AndroidViewModel {

MyRepository repo;

public FactsViewModel(@NonNull Application application) {
    super(application);

    repo = new MyRepository(application);
}

public LiveData<List<Facts>> getAllFacts(){

    return repo.getMutableLiveData();
  }
}

HomeFragment.class

public class HomeFragment extends Fragment {

RecyclerView recycle;
FactsAdapter adapter;
FactsViewModel viewModel;

AdView adView;
AdRequest adRequest;

public HomeFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_home, container, false);

    recycle = view.findViewById(R.id.recycle);
    LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
    mLayoutManager.setReverseLayout(true);
    mLayoutManager.setStackFromEnd(true);
    recycle.setLayoutManager(mLayoutManager);
    recycle.setHasFixedSize(true);

    viewModel = new ViewModelProvider(getActivity()).get(FactsViewModel.class);

    return view;
     
}

How can I resolve this error?


Solution

  • It errors because the Activity is not yet created.

    Moving the ViewModel instantiation to onActivityCreated lifecycle is the key

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
       viewModel = new ViewModelProvider(getActivity()).get(FactsViewModel.class);
    }