ViewModelProviders is deprecated in 1.1.0
Asked Answered
C

30

246

Looking at the Google docs for ViewModel, they show the below sample code on how to get a ViewModel:

val model = ViewModelProviders.of(this).get(MyViewModel::class.java)

When using the latest dependency android.arch.lifecycle:extensions:1.1.1 there is no such class ViewModelProviders.

Going to the documentation for ViewModelProviders, I saw a comment saying:

This class was deprecated in API level 1.1.0. Use ViewModelProvider.AndroidViewModelFactory

The problem is, when trying to use ViewModelProvider.AndroidViewModelFactory, cannot find an equivalent of method to get the instance of the ViewModel.

What i tried doing:

ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(PlayerViewHolder::class.java)

Hence the name of the method create, I get a new instance of the ViewModel every-time I call it, which is not what I am after.

Any ideas what is the replacement of deprecated code above?

Contractor answered 23/12, 2018 at 12:53 Comment(1)
use singleton pattern or change to AndroidXBobinette
F
47

UPDATE 2020-06-16: Presently ViewModelProviders is deprecated and should no longer be used. This question and answer were from late 2018, when that was not the case. This question and answer are also for the older Architecture Components edition of ViewModelProviders, not the AndroidX edition.


When using the latest dependency android.arch.lifecycle:extensions:1.1.1 there is no such class ViewModelProviders.

Yes, there is. To demonstrate this:

  • Create a new project in Android Studio 3.2.1 (with Kotlin, minSdkVersion 21, "empty activity" template)

  • Add android.arch.lifecycle:extensions:1.1.1 to the dependencies of the app module

This will give you an app/build.gradle like:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.commonsware.myandroidarch"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    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.android.support.constraint:constraint-layout:1.1.3'
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    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'
}

You will then see that library show up in "External Libraries" with that class:

External Libraries

And you will be able to reference that class:

package com.commonsware.myandroidarch

import android.arch.lifecycle.ViewModelProviders
import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val provider = ViewModelProviders.of(this)
  }
}

Going to the documentation for ViewModelProviders, I saw a comment saying: This class was deprecated in API level 1.1.0. Use ViewModelProvider.AndroidViewModelFactory

That comment is underneath the ViewModelProviders.DefaultFactory class entry and refers to that class, not ViewModelProviders:

Documentation Screenshot

Any ideas what is the replacement of deprecated code above?

Use ViewModelProviders.

Freetown answered 23/12, 2018 at 13:8 Comment(2)
@TareKKhoury: That would explain it! Keeping track of which modules need which dependencies definitely can be a challenge. I'm glad to hear that you got it working!Freetown
This is not true anymore, ViewModelProviders.of() no longer exists.Autogamy
C
477

I use lifecycle-extensions 2.2.0 version:

implementation "androidx.lifecycle:lifecycle-extensions:2.2.0" 

It should work, using ViewModelProvider constructor.

// With ViewModelFactory   
val viewModel = ViewModelProvider(this, YourViewModelFactory).get(YourViewModel::class.java)


//Without ViewModelFactory
val viewModel = ViewModelProvider(this).get(YourViewModel::class.java)

2020/5/15 Update

I found another elegant way to achieve this, Android KTX can help

implementation "androidx.fragment:fragment-ktx:1.2.4"
val viewmodel: MYViewModel by viewModels()
val viewmodel: MYViewModel by viewModels { myFactory } //With factory

Ref: https://developer.android.com/reference/kotlin/androidx/fragment/app/package-summary#viewmodels

2020/06/25: corrected the case of the delegate

Chandlery answered 9/8, 2019 at 9:24 Comment(12)
I am kind of sick of the constant "depreciation" cycle by Google.Invertase
ViewModelProviders.of() has been deprecated. You can pass a Fragment or FragmentActivity to the new ViewModelProvider(ViewModelStoreOwner) constructor to achieve the same functionality. (aosp/1009889)Schizophyceous
Java equivalent: YourViewModel viewModel = new ViewModelProvider(this).get(YourViewModel.class);Parliamentarian
I worry if some day Google will deprecate the TextView or EditText and introduce a new Component.Vole
androidx lifecycle-viewmodel 2.1.0 does not have a constructor without a factory. using simply (this) does not work. ViewModelProvider(ViewModelStoreOwner, Factory) and ViewModelProvider(ViewModelStore, Factory) are the only constructorsBatsman
Any reason for the change?Erythritol
When software evolves, old implementations get deprecated. This is natural, there is no use in fighting that.Electoral
@AFD true. Some of google's libraries change API every month, like WebRTC android. Very frustrating when trying to learn the framework from tutorialsGupton
So we hae to create new objects each time?Uncommitted
The code val viewmodel: MYViewModel by viewModels { myFactory } and myFactory only worked when used as properties, for me. When I tried to assign them both as local variables in a function, this didn't work. Why is that?Elenaelenchus
I've been programming in Android for years and it's the most depressing thing ever.Forenoon
Note: as per the Lifecycle 2.2.0 release notes, the lifecycle-extensions artifact is no longer published. The APIs in lifecycle-extensions have been deprecated. Instead, add dependencies for the specific Lifecycle artifacts you need.Watkins
W
104

As @FantasyFang mentioned in his answer, use the lastest version for the lifecycle:lifecycle-extensions which in this moment is 2.2.0-alpha03. So you should add in your build.gradle file the following line:

implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha03' 

For those who are using Java, to solve this, pass those arguments directly to ViewModelProvider's constructor:

MyViewModel viewModel = new ViewModelProvider(this, myViewModelFactory).get(MyViewModel.class);

Or if you don't use a factory, simply use:

MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);

Without passing your the factory object.

Wivestad answered 14/8, 2019 at 13:31 Comment(1)
You should be using the following in build.gradle: implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version" As noted in developer.android.com/jetpack/androidx/releases/lifecycle The APIs in lifecycle-extensions have been deprecated. Instead, add dependencies for the specific Lifecycle artifacts you need.Disjuncture
N
78

Import

Deprecated From:

import androidx.lifecycle.ViewModelProviders;

To:

import androidx.lifecycle.ViewModelProvider;

Using

Deprecated From:

ViewModelProviders.of(this, provider).get(VM::class.java)

To:

ViewModelProvider(this, provider).get(VM::class.java)
Normalcy answered 28/2, 2020 at 19:58 Comment(2)
exactly what I was looking for.Cittern
Perfect. This should be the accepted answer.Iloilo
D
61

As of 2.2.0. the lifecycle-extensions has been deprecated. Refer to Google Documentation.

This is the cut from the page:

The APIs in lifecycle-extensions have been deprecated. Instead, add dependencies for the specific Lifecycle artifacts you need.

The new libraries are:

// ViewModel and lifecycle support for java
implementation "androidx.lifecycle:lifecycle-viewmodel:${versions.lifecycle}"
implementation "androidx.lifecycle:lifecycle-livedata:${versions.lifecycle}"

// ViewModel and lifecycle support for kotlin
implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:${versions.lifecycle}"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:${versions.lifecycle}"

The new code for JAVA:

viewModel = new ViewModelProvider(this).get(MyViewModel.class);

Or for Kotlin:

viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
Disjuncture answered 4/2, 2020 at 23:4 Comment(2)
Do we keep the ViewModelProvider isntsance or have to recreate it again, in which case, all underlying instances will also be destroyed. I don't the reason of re-creating it if the idea is to watch the lifecycle of the fragment/activityUncommitted
Thanks for including Java - some of us still have to maintain legacy code.Tailpiece
F
47

UPDATE 2020-06-16: Presently ViewModelProviders is deprecated and should no longer be used. This question and answer were from late 2018, when that was not the case. This question and answer are also for the older Architecture Components edition of ViewModelProviders, not the AndroidX edition.


When using the latest dependency android.arch.lifecycle:extensions:1.1.1 there is no such class ViewModelProviders.

Yes, there is. To demonstrate this:

  • Create a new project in Android Studio 3.2.1 (with Kotlin, minSdkVersion 21, "empty activity" template)

  • Add android.arch.lifecycle:extensions:1.1.1 to the dependencies of the app module

This will give you an app/build.gradle like:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.commonsware.myandroidarch"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    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.android.support.constraint:constraint-layout:1.1.3'
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    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'
}

You will then see that library show up in "External Libraries" with that class:

External Libraries

And you will be able to reference that class:

package com.commonsware.myandroidarch

import android.arch.lifecycle.ViewModelProviders
import android.support.v7.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val provider = ViewModelProviders.of(this)
  }
}

Going to the documentation for ViewModelProviders, I saw a comment saying: This class was deprecated in API level 1.1.0. Use ViewModelProvider.AndroidViewModelFactory

That comment is underneath the ViewModelProviders.DefaultFactory class entry and refers to that class, not ViewModelProviders:

Documentation Screenshot

Any ideas what is the replacement of deprecated code above?

Use ViewModelProviders.

Freetown answered 23/12, 2018 at 13:8 Comment(2)
@TareKKhoury: That would explain it! Keeping track of which modules need which dependencies definitely can be a challenge. I'm glad to hear that you got it working!Freetown
This is not true anymore, ViewModelProviders.of() no longer exists.Autogamy
M
37

Early in 2020, Google have deprecated the ViewModelProviders class, in version 2.2.0 of the androidx lifecycle library.

It's no longer necessary to use ViewModelProviders to create an instance of a ViewModel, you can pass your Fragment or Activity instance to the ViewModelProvider constructor instead.

If you use the code like:

val viewModel = ViewModelProviders.of(this).get(CalculatorViewModel::class.java)

you'll get a warning that ViewModelProviders has been deprecated.

To avoid using deprecated libraries, make the following changes:

  1. In the build.gradle (Module: app) file, use version 2.2.0 of the lifecycle components:

    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation "androidx.activity:activity-ktx:1.1.0"
    

    If you want to use the ViewModel from a Fragment instead, use

    implementation "androidx.fragment:fragment-ktx:1.2.2"
    

    fragment-ktx automatically includes activity-ktx, so you don't need to specify both in the dependencies.

  2. You need to specify Java 8 in the android section :

    android {
        compileSdkVersion 28
        defaultConfig {
            applicationId "com.kgandroid.calculator"
            minSdkVersion 17
            targetSdkVersion 28
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner 
        "androidx.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 
               'proguard-rules.pro'
            }
        }
    
        kotlinOptions { jvmTarget = "1.8" }
    }
    
  3. In your Fragment or Activity, change the import to:

    import androidx.activity.viewModels

  4. The code to create a ViewModel then becomes:

    val viewModel: CalculatorViewModel by viewModels()
    

    instead of

    val viewModel = ViewModelProviders.of(this).get(CalculatorViewModel::class.java)
    

    Use the viewModel object as :

    val viewModel: CalculatorViewModel by viewModels()
    
    viewModel.newNumber.observe(this, Observer<String> { 
        stringResult -> newNumber.setText(stringResult) 
    })
    

    where newNumer is a LiveData object

    In a Fragment that you want to share the Activity's ViewModel, you'd use

    val viewModel: CalculatorViewModel by activityViewModels()
    

That's the equivalent of passing the Activity instance in the (deprecated) ViewModelProviders.of() function.

Mindi answered 13/3, 2020 at 12:55 Comment(0)
A
26

ViewModelProviders.of() has been deprecated. enter image description here

Use ViewModelProvider constructors directly as they now handle the default ViewModelProvider.Factory role.

 mainActivityViewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
Anzus answered 28/12, 2019 at 22:21 Comment(0)
G
20

Probably you can just use:

val viewModel = ViewModelProvider(this, ViewModelProvider.NewInstanceFactory()).get(MyViewModel::class.java)

without needing to add android.arch.lifecycle:extensions:1.1.1 as the dependency.

Gizmo answered 24/7, 2019 at 14:2 Comment(0)
I
15

Actually, what does the ViewModelProviders.of() method do under the hood?

@Deprecated
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull Fragment fragment) {
    return new ViewModelProvider(fragment);
}

It takes Fragment as an argument, creates ViewModelProvider object and passes the fragment directly to ViewModelProvider constructor.

We can use the same way too.

E.g. Before:

OurViewModel mOurViewModel = ViewModelProviders.of(this).get(OurViewModel.class);

After:

OurViewModel mOurViewModel = new ViewModelProvider(this).get(OurViewModel.class);
Immeasurable answered 21/3, 2020 at 13:1 Comment(1)
If you implement a Factory, you have another way: ViewModelProvider has a constructor which expects both a ViewModelStoreOwner and a Factory.Bug
S
14

In case you watch a video from Udacity where you create a GameViewModel and you do not want to write deprecated code just replace:

viewModel = ViewModelProviders.of(this).get(GameViewModel::class.java)

with the following code:

viewModel = ViewModelProvider(this).get(GameViewModel::class.java)
  

and return back to reading ASAP!!

Sierra answered 21/10, 2020 at 11:43 Comment(0)
Y
13

Yes @Tarek, it is deprecated. Use now with AndroidX:

val yourViewModel = ViewModelProvider.NewInstanceFactory().create(YourVideoModel::class.java)
Yorkshire answered 11/4, 2019 at 17:34 Comment(1)
This answer is wrong. You should be using a ViewModelProvider(viewModelStoreOwner, factory).get(YourVideoModel::class.java) otherwise your onCleared() won't work correctly, and ViewModel won't be kept across config change. Do not use this answer.Autogamy
P
12

Use ViewModelProvider directly instead of user ViewModelProviders.of() as mentioned in the docs.

ViewModelProvider(this).get(XViewModel::class.java)

https://developer.android.com/reference/androidx/lifecycle/ViewModelProviders

Purple answered 2/12, 2019 at 14:44 Comment(0)
S
9

I'm using android X and also had this issue.

First of all, you should add these dependencies to your Gradle:

implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"
kapt "androidx.lifecycle:lifecycle-compiler:$lifecycle_version" 

In my case, the $lifecycle_version was 2.2.0-rc02

Second: The import for the ViewModelProvider should be:

import androidx.lifecycle.ViewModelProvider

Than you can initial your vIewModel like the examples below:

val viewModel = ViewModelProvider(this, YourFactoryInstace).get(MainViewModel::class.java)

val viewModel = ViewModelProvider(this).get(MainViewModel::class.java)
Shirk answered 7/1, 2020 at 8:27 Comment(2)
thank you for your answer , but when i use it then viewmodel observe and fields databinding is no longer workOma
I believe androidx.lifecycle:lifecycle-compiler is obsoleted by androidx.lifecycle:lifecycle-common-java8.Drivel
M
7

If you use Kotlin, you can use the property delegate viewModels() like this:

val viewModel: YourViewModel by viewModels()

Source: https://forums.bignerdranch.com/t/solution-to-deprecated-method-viewmodelproviders-of/16833

Macon answered 2/1, 2020 at 12:44 Comment(0)
K
6

Use this:

YourViewModel yourViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(YourViewModel.class);
Khz answered 17/5, 2020 at 18:7 Comment(1)
will this not create new instance every time when on create called? suppose lifcyle like this, stop , onCreate ?Stupid
L
5

You can use this instead:

viewModel= ViewModelProvider(this).get(YourViewModel::class.java)

"this" in the parentheses is the owner of YourViewModel instance.

Leontina answered 12/4, 2020 at 13:29 Comment(0)
L
3

I'm no expert but i have a line of code that solved my problem in Java. Hope this helps someone.

viewModel = 
new ViewModelProvider
.AndroidViewModelFactory(getApplication())
.create(ViewModel.class);

As i said i would love to provide more details, but this fixed this problem for me.

Ledger answered 17/2, 2020 at 11:22 Comment(5)
This code is wrong, onCleared() won't be called this way and your ViewModel will be recreated each time (not kept for config changes).Autogamy
Can you explain a bit more with a certain example, what would fix my mistake? Please, paste a reference to the explanation or anything that would make things clearerLedger
viewModel = new ViewModelProvider(this).get(MyViewModel.class). If your AndroidViewModel doesn't get the Application, then you have a version mismatch between Lifecycle and Activity/Fragment.Autogamy
Ok, so calling getApplicationContext is wrong? Should it just be getContext?Ledger
The issue is creating a new ViewModelProvider.AndroidViewModelFactory( instead of a new ViewModelProvider(.Autogamy
M
3

This answer is for Java but you can understand main point. Solution is that you need use ViewModelProvider because ViewModelProviders deprecated:

//Do not forget import it.
import androidx.lifecycle.AndroidViewModel;

ViewModelProvider.AndroidViewModelFactory(getApplication()).create(YourViewModel.class);

Example usage is:

YourViewModel yourViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(YourViewModel.class);

Also, do not forget update Gradle Dependencies: Check here for last versions of them

implementation 'androidx.lifecycle:lifecycle-viewmodel:2.2.0'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.2.0'

!!! However, be careful because some answers recommend this solution but it did not work for me:

yourViewModel = new ViewModelProvider(this).get(YourViewModel.class);

Because when I used this way, I got below Error Message:

Caused by: java.lang.RuntimeException: Cannot create an instance of class com.canerkaseler.mvvmexample.ViewModel

Mischa answered 22/4, 2020 at 13:24 Comment(3)
This answer is wrong. You need to pass the factory to a ViewModelProvider. If you directly invoke create, then onCleared() won't work correct.Autogamy
In fact, you literally just said not to use the correct answer. Sounds like you had a mismatch between your androidx.core and your androidx.lifecycle dependencies.Autogamy
Normally I wrote the factory to ViewModelProvider. However, you deleted it. ContactViewModel contactViewModel = new ViewModelProvider.AndroidViewModelFactory(getApplication()).create(ContactViewModel.class); Why did you delete it on my answer? You passed wrong codes.Mischa
I
3

Update: July 20 2022

private lateinit var binding: FragmentHomeBinding
    private lateinit var homeMvvM : HomeViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        homeMvvM = ViewModelProvider(this)[HomeViewModel::class.java]

this works for me.

Interface answered 21/7, 2022 at 2:42 Comment(0)
K
2

When you use dagger then u'll pass factory in constructor

  MobileViewModel mobileViewModel = new ViewModelProvider(this,providerFactory).get(MobileViewModel.class);
Kincaid answered 30/4, 2020 at 7:25 Comment(0)
D
2

I kept trying and ended up with this solution in Kotlin, you should be able to try it in java too.

MainActivity.kt

 val provider : ViewModelProvider = ViewModelProvider(this)
 val VM = provider.get(ViewModelClass::class.java)

build.gradle

implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0"
implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.3.0"

Current version of the lifecycle libraries is 2.3.0 as of 2/2/2021, Refer to https://developer.android.com/jetpack/androidx/releases/lifecycle to check for current version.

Dowager answered 5/1, 2021 at 14:34 Comment(0)
S
2

I'm using factory.

ViewModelProvider.AndroidViewModelFactory
            .getInstance(getApplication())
            .create(DashboardViewModel.class);
Sarajane answered 15/5, 2021 at 11:38 Comment(0)
R
1

Simply update from

ViewModelProviders.of(this, provider).get(MainActivityViewModel::class.java)

to

ViewModelProvider(this, provider).get(MainActivityViewModel::class.java)

Reneta answered 5/9, 2021 at 17:35 Comment(0)
M
1
//Activity ktx
implementation 'androidx.activity:activity-ktx:1.5.1'

//Fragment ktx
implementation 'androidx.fragment:fragment-ktx:1.5.1'

Simplest way of creating view models:

class MyViewModel() : ViewModel() {

}

class SomeActivity:AppCompatActivity(){
  private val viewModel: MyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_some)
}
}

View Model With Constructor Arguments:

class MyViewModel(list:List<String>) : ViewModel() {


 class Factory(list:List<String>) : ViewModelProvider.Factory {
        @Suppress("unchecked_cast")
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            return MyViewModel(list) as T
        }
    }
}
class SomeActivity:AppCompatActivity(){

  private val viewModel: MyViewModel by viewModels(){
MyViewModel.Factory(listOf<String>("a"))}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}
}
Millsap answered 13/8, 2022 at 1:37 Comment(0)
C
0

I was facing the same issue. if anything doesn't work try this piece of code into your oncreate and edit it according to your file and boom you are gtg

val model = ViewModelProvider(viewModelStore,ViewModelProvider.AndroidViewModelFactory.getInstance(application)).get(MainActivityViewModel::class.java)

// you just need to change the model class

Crossbreed answered 10/3, 2021 at 20:29 Comment(1)
Please read How to answer and update your question.Unstrained
R
0

You can use something like this:

private  val sharedViewModel: SharedViewModel by viewModels(ownerProducer = { requireActivity() })


ownerProducer = { requireActivity() } // This is only required if you want to share same view model among different fragments.
Romine answered 9/11, 2021 at 10:16 Comment(0)
P
0

I am using Library of Lifecycle 2.3.1 and add below dependency in build.gradle (Module-level)

implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.3.1'
implementation 'androidx.lifecycle:lifecycle-extensions-ktx:2.2.0'
implementation 'androidx.activity:activity-ktx:1.4.0'
implementation 'androidx.fragment:fragment-ktx:1.3.6'

Declare viewModels() in your Kotlin code as per below:

import androidx.fragment.app.viewModels

private val cartViewModel: CartViewModel by viewModels()
Patency answered 15/11, 2021 at 9:37 Comment(0)
A
0

Try adding this code in your build.gradle module level

 android {
 kotlinOptions {
    freeCompilerArgs += [
        '-Xjvm-default=enable'
    ]
  }   
}
Algo answered 21/9, 2022 at 9:32 Comment(0)
T
-1

Try this...

 LocationViewModel locationViewModel = new ViewModelProvider(this).get(LocationViewModel.class);
Thegn answered 28/2, 2020 at 12:37 Comment(0)
P
-7

it should work this way

 viewModel = ViewModelProviders.of(this@MainActivity).get(MainActivityViewModel::class.java)
Parcae answered 23/12, 2018 at 13:7 Comment(2)
While your code would instance the class is will not create the connection to the view state required to have the View Model class to correctly respond to life cycle events. You need to instance View Models in the correct manner so they respond and honor life cycles of their parents else they be recreated fresh and blank each time.Disjuncture
As noted above by the OP and others; the ViewModelProviders class has been deprecated. See: developer.android.com/reference/androidx/lifecycle/…Disjuncture

© 2022 - 2024 — McMap. All rights reserved.