0
votes

As a seasoned iOS developer making my first Android application, I'm attempting to use an AndroidViewModel to allow cross-fragment/cross-configuration-change persistence of my runtime state. I'm using AndroidViewModel rather than ViewModel because I need access to the application context to load some static resources.

This is my AndroidViewModel subclass:

class QuestsViewModel(application: Application) : AndroidViewModel(application) {
  // Some member state variables
}

And I'm trying to access it from my main activity's onCreate like so:

val viewModel = ViewModelProviders.of(this,
  ViewModelProvider.AndroidViewModelFactory(this.application))
    .get(QuestsViewModel::class.java)

But I get the compiler error:

Type parameter bound for T in operator fun get(p0: Class): T is not satisfied: inferred type QuestsViewModel! is not a subtype of ViewModel!

I'm confused as to why it thinks my custom ViewModel class is not a subclass, when ApplicationViewModel (which I inherit from) directly inherits from ViewModel?

For clarity I'm attempting to write this project entirely in Kotlin (if possible). Just in case it's relevant, my gradle dependencies are:

    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.google.android.gms:play-services-maps:16.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:support-v4:28.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'com.android.support:recyclerview-v7:28.0.0'
    implementation 'com.android.volley:volley:1.1.1'

    def lifecycle_version = "2.0.0"
    implementation "android.arch.lifecycle:extensions:1.1.1"
    implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
    kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
1

1 Answers

0
votes

For future reference for anyone who finds this: My problem was importing the AndroidViewModel class from two different packages in the two source files - one from the androidx namespace and one not.

Migrating all my gradle packages to androidx versions (where possible) and updating all the import statements resolved the problem.