0

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;
    }
}
Supriya
  • 25
  • 6

2 Answers2

1

You can annotate your model class with below annotation

@NoArgsConstructor

You will get more idea about lombok , NoArgsConstructor and many more annotations using this linklombok

Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38
0

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...

Vishnu
  • 663
  • 3
  • 7
  • 24