Search code examples
androidandroid-studioauthenticationandroid-activityviewmodelproviders

Cannot resolve symbol 'ViewModelProvider'


I wanted to use android studio's given Login Activity (File>New>Activity>Login Activity), but when I added the activity I got the error for ViewModelProvider. I tried looking for the solution but everything I found was mostly related to ViewModelProviders (with final "s", deprecated) or said to add certain dependencies to the build module, neither of which worked. Any help please?

import androidx.lifecycle.ViewModelProvider;
public class LoginActivity extends AppCompatActivity {

    private LoginViewModel loginViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        loginViewModel = new ViewModelProvider(this, new LoginViewModelFactory())
                .get(LoginViewModel.class);
    //...
    }
//...
}

My code looks something like this, I get the error from the import (and every instance) of ViewModelProvider. I already tried to add the dependencies suggested and synced, but nothing seems to work!


Solution

  • If you use Jetpack, you should use this:

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

    link