3

Hello I am new to MVVM in android and working with livedata. I am trying to create an instance of my viewmodel. I feel the issue is that i have not passed my repository to my viewmodel constructor. I keep getting cannot create instance of viewmodel. I am not sure how to do this here is my viewmodel and its creation.

public class UserProfileViewModel extends ViewModel {
    private LiveData<User> user;
    private UserRepository userRepository;

    @Inject
    public UserProfileViewModel(UserRepository userRepo){
        this.userRepository = userRepo;
    }

    public void init(String userId){
        if (this.user != null) {
            return;
        }
        user = userRepository.getUser(userId);
    }

    public LiveData<User> getUser() {
        return this.user;
    }
}


//create view model in fragment
viewModel = ViewModelProviders.of(this).get(UserProfileViewModel.class);
viewModel.init(mUserId);
inhaler
  • 415
  • 2
  • 7
  • 20

2 Answers2

1

here is a proper explanation of using view model ->

Sharing data between fragments using new architecture component ViewModel

hope this helps

Anjani Mittal
  • 507
  • 1
  • 7
  • 19
1

for anyone wandering, the solution to this problem can be found there https://stackoverflow.com/a/49087002/6692278

inhaler
  • 415
  • 2
  • 7
  • 20