Using viewModels()

Hi everyone, the problem is the following, in listing 10.3, when I create a CrimeListFragment class and associate it with a CrimeListViewModel, I cannot initialize it using viewModels() - this is marked in red. But when I create CrimeListFragment as a subclass, for example, FragmentActivity(), everything works out.

package com.example.criminalintent

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.activity.viewModels

private const val TAG = “CrimeListFragment”
class CrimeListFragment: Fragment(){
private val crimeListViewModel:CrimeListViewModel by viewModels() // Unresolved reference. //None of the following candidates is applicable because of receiver type mismatch:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    Log.d(TAG, "Total crimes: ${crimeListViewModel.crimes.size}")
}}

How to fix it?

The issue might be due to the improper context or incorrect use of viewModels(). Ensure that CrimeListFragment is correctly extending Fragment and try using by viewModels() within the fragment’s onCreate method.
At Your Injury Case Law Firm, we specialize in handling personal injury cases with expertise. Visit yourinjurycase.com for dedicated legal support and maximize your compensation.

I’m guessing it’s because you’re importing activity.viewmodels but you want it for a fragment, change this line :

import androidx.activity.viewModels
to :
import androidx.fragment.app.viewModels