1

I am currently learning Kotlin on the developer.android.com

Here is the code :

class GameViewModel : ViewModel()  {
init {
    Log.d("GameFragment", "GameViewModel created!")
}

private val viewModel: GameViewModel by viewModels()
private var score = 0
private var currentWordCount = 0
private var _currentScrambledWord = "test"
public val currentScrambledWord: String
    get() = _currentScrambledWord

override fun onCleared() {
    super.onCleared()
    Log.d("GameFragment", "GameViewModel destroyed!")
}

}

The image of the code

and I get this error when I try to use the viewModels delegate.

[<html>Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:<br/>public inline fun &lt;reified VM : ViewModel&gt; Fragment.viewModels(noinline ownerProducer: () -&gt; ViewModelStoreOwner = ..., noinline factoryProducer: (() -&gt; ViewModelProvider.Factory)? = ...): Lazy&lt;TypeVariable(VM)&gt; defined in androidx.fragment.app]

This is my configuration :

implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.2.1'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.navigation:navigation-fragment-ktx:2.3.5'
// LiveData
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
// ViewModel
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.fragment:fragment-ktx:1.3.6'
implementation 'androidx.activity:activity-ktx:1.3.1'

I found this post : 'by viewModels()' Kotlin property delegate unresolved reference

But it is not resolving my error.

Does anyone could help me please ?

  • This delegate is only for fragments and activities. What are you trying to achieve by referencing `GameViewModel` from within `GameViewModel` anyway? – Pawel Sep 29 '21 at 17:02
  • Damned -_- You right I try to declare in the wrong class ! thanks. Now it's working – Nicolas Briand Sep 29 '21 at 17:12

1 Answers1

0

The issue is being caused by trying to access the ViewModel from inside a ViewModel Class.

The by-delegate is meant for accessing the ViewModel from an Activity or a Fragment. For instance, you can use this delegate from an Activity.

class MainActivity : AppCompatActivity() {

    private val viewModel: GameViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
Tonnie
  • 4,865
  • 3
  • 34
  • 50