user12786901
user12786901

Reputation:

Cannot access ViewModel method from fragment

Probably it has a simple solution that I cant see. I have a fragment with a ViewModel, The Viewmodel has a method inside of it that I want to call from my fragment and supply the arguments for. but when I try to call the method it shows an error "Unsolved Reference"

 class DetailFragmentViewModel : ViewModel() {

       private val repo = Crepository.get()
       private val itemIdlivedata = MutableLiveData<UUID>()
       var crimeLiveDate: LiveData<Crime?> = Transformations.switchMap(itemIdlivedata){ it -> 
       repo.getitem(it) }
    fun LoadItem(itemuuid:UUID){
     itemIdlivedata.value = itemuuid
                          }
                  }

Fragment Class:

  private val crimeDetailVM : ViewModel by lazy {
    ViewModelProvider(this).get(DetailFragmentViewModel::class.java)
}
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
     ...

   crimeDetailVM.LoadItem <- Unsolved Reference 

}

Thanks for the help!

EDIT:IT HAS A SIMPLE SOLUTION, I DID NOT CAST THE VIEW MODEL TO THE VIEW MODEL CLASS,THANKS FOR THE HELP EVERYONE

Upvotes: 1

Views: 1779

Answers (2)

G&#246;kberk Yağcı
G&#246;kberk Yağcı

Reputation: 436

You are doing downcasting DetailFragmentViewModel to ViewModel. That is why you are not accessing to DetailFragmentViewModel methods.

Use

private val crimeDetailVM : DetailFragmentViewModel by lazy {
    ViewModelProvider(this).get(DetailFragmentViewModel::class.java)
}

Instead of

private val crimeDetailVM : ViewModel by lazy {
    ViewModelProvider(this).get(DetailFragmentViewModel::class.java)
}

Also this way is not idiomatic i suggest you to use kotlin extension

val viewModel by viewModels<DetailFragmentViewModel>()

But before do that you need to add the dependency which is Fragment KTX to your app gradle file.

https://developer.android.com/kotlin/ktx

Upvotes: 1

Harpreet Grewal
Harpreet Grewal

Reputation: 3

You need activity context try: ViewModelProvider(requireActivity()).get(DetailFragmentViewModel::class.java)

you can use also extend view model by ActivityViewModel eg.-> class DetailFragmentViewModel(application:Application) : AndroidViewModel(applivation){}

Upvotes: 0

Related Questions