0

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??

Diego Perez
  • 2,188
  • 2
  • 30
  • 58

1 Answers1

1

But it's complaining that "this" cannot be cast to ViewModelStoreOwner.

What am I doing wrong?

You're providing an argument of a different type then what is expected.

Your question is incomplete because you didn't show what this is, but apparently it is not a ViewModelStoreOwner.

Looking at the documentation for this class, you can see a list of all the classes that extend it. Your this would have to be one of these classes, or a class you defined that extends one of these classes.

If you're in an Activity you defined, it should extend AppCompatActivity.

If you're in a Fragment you defined, it should extend Fragment.

dominicoder
  • 9,338
  • 1
  • 26
  • 32
  • Thanks @dominicoder, I was extending Activity instead of AppCompactActivity. If I extend AppCompactActivity it doesn't complaint anymore, but as soon as my app starts it throws an exception of type: You need to use a Theme.AppCompat theme (or descendant) with this activity. In my MainActivity. I'm not using Theme.AppCompat in my app, must I from now on? Should I include it in manifest or where? The fact is I'm already using android:theme="@style/Theme.myTheme.TitleBar" in my AndroidManifest.xml, and cannot remove it as I'm using custom title bar :s – Diego Perez Sep 26 '21 at 23:35
  • Check [this](https://stackoverflow.com/a/39604946/5978440) @DiegoPerez – Sniffer Sep 27 '21 at 04:04
  • Please ask a new question instead of threading an existing question. – dominicoder Sep 29 '21 at 06:23