Android MVVM: Cannot instantiate viewmodel
I'm new to MVVM, and trying to implement it little by little into my app, and for that I've started watching some MVVM tutorials on YouTube, but I'm having problems when trying to instantiate the viewmodel into my activity.
I already know lifecycle imports are no longer needed in build.gradle as of 2021, and in fact ViewModel class is autommatically detected and imported like in the next class:
import androidx.lifecycle.ViewModel;
public class LoginViewModel extends ViewModel
{
}
Then in my LoginActivity class I'm trying to instantiate the vm the next way:
LoginViewModel loginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
But it's complaining that "this" cannot be cast to ViewModelStoreOwner.
What's the problem?
Edit 1:
I tried the @dominicoder and if I extend AppCompatActivity in my BaseActivity class it works, but I get
"You need to use a Theme.AppCompat theme (or descendant) with this activity"
Exception as soon as the app starts, but cannot set an AppCompat theme in AndroidManifest because I'm already using one theme for custom title actionbar.
android:theme="@style/Theme.myTheme.TitleBar"
Anyway I've also tried next @Sniffer suggestion (just in case) to no avail:
How to fix: "You need to use a Theme.AppCompat theme (or descendant) with this activity"
Does that means I won't be able to migrate my app to MVVM architecture?
Is extending AppCompatActivity the only solution??
from Recent Questions - Stack Overflow https://ift.tt/39KvSmu
https://ift.tt/eA8V8J
Comments
Post a Comment