I'm getting a NullPointerException when I tried to instantiate MyViewModel into MyFragment:
public class MyFragment extends Fragment {
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
myViewModel = new ViewModelProvider(this, new MyViewModelFactory(
requireActivity().getApplication(), 0))
.get(MyViewModel.class);
}
The stack trace seems to be pointing out the last line .get(MyViewModel.class); and I can't get it to work for days now. I did null checks on getApplication() by using System.out.println() and a value is returned, so I don't think that is the problem. This approach that I used worked just fine when I do this on an activity, but when I tried to implement this on a Fragment, a NullPointerException occured. What should I change to make this work?
Here's how I did my ViewModelFactory class:
public class MyViewModelFactory implements ViewModelProvider.Factory {
private Application application;
private int intValue;
public MyViewModelFactory(Application paramApplication, int paramIntValue) {
application = paramApplication;
intValue = paramIntValue;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
if (modelClass == MyViewModel.class) {
return (T) new MyViewModel(application, intValue);
}
return null;
}
}
My ViewModel class:
public class MyViewModel extends AndroidViewModel {
private MyDataModelRepository myDataModelRepository;
private LiveData<List<MyDataModel>> liveDataListMyDataModel;
public MyViewModel(@NonNull Application application, int intValue) {
super(application);
myDataModelRepository= new myDataModelRepository(application);
if (intValue> 0) {
liveDataListMyDataModel= myDataModelRepository.getLiveDataListMyDataModelWhere(intValue);
} else {
liveDataListMyDataModel= myDataModelRepository.getLiveDataListMyDataModel();
}
}
}
Logcat- Vishnu