Search code examples
javaandroidmvvmandroid-roomviewmodel

Android view model class has no zero argument constructor,Instantiation Exception in fragment


i have a view model class and i need to instantiate it in a fragment. But I am getting :

java.lang.RuntimeException: Cannot create an instance of class com.example.project.favourites.FavViewModel

and

Caused by: java.lang.InstantiationException: java.lang.Class<com.example.project.favourites.FavViewModel> has no zero argument constructor

This is the line causing crash:

favViewModel= new ViewModelProvider(this).get(FavViewModel.class); 
(This line is within onViewCreated in fragment)
   

pls help!!!!!

Below is FavViewModel Class

public class FavViewModel extends AndroidViewModel {
    private FavRepository repository;
    private LiveData<List<FavItem>> allFav;

    public FavViewModel(@NonNull Application application) {
        super(application);
        repository=new FavRepository(application);
        allFav=repository.getAllFav();
    }


    public void insert(FavItem favItem){
        repository.insert(favItem);
    }

    public void delete(FavItem favItem){
        repository.delete(favItem);
    }

    public void deleteAll(){
        repository.deleteAll();
    }
    public LiveData<List<FavItem>> getAllFav(){
        return allFav;
    }
}

Solution

  • Try using this...

    Initialise ViewModel like this. You need to also pass ViewModelFactory with ViewModelProvider constructor.

    favViewModel = new ViewModelProvider(this,
                    new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(FavViewModel.class);
    

    Hope this helps. Feel free to ask for clarifications...