3

I'm trying to call a method that I've created in my ViewModel class but I'm not able to access it in my MainActivity where I've initialized my ViewModel.

This is my ViewModel class

public class MovieViewModel extends AndroidViewModel {

private MovieRepository movieRepository;
public List<Movie> movieList;

public MovieViewModel(@NonNull Application application) {
    super(application);
    movieRepository = new MovieRepository();
}

public List<Movie> getMovieList(String sortChoice, int pageNumber) {
    movieList = movieRepository.getMovieList(sortChoice,pageNumber);
    return movieList;
}
}

This is part of MainActivity

    private ViewModel mViewModel;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        pageNumber = 1;
        sharedPref = this.getPreferences(Context.MODE_PRIVATE);
        String defaultSort = MovieConstants.POPULAR;
        choiceOfSorting = sharedPref.getString(PREF_SORT_KEY, defaultSort);

        mViewModel = ViewModelProviders.of(this).get(MovieViewModel.class);
`

When I try calling the method getMovieList with the line

mViewModel.getMovieList(someVariable, someVariable); 

it shows in red saying - Cannot resolve symbol 'getMovieList'

1
  • you are saving viewmodel in ViewModel instance, use MovieViewModel instead Commented Aug 28, 2018 at 13:57

3 Answers 3

2

You're assigning ViewModelProviders.of(this).get(MovieViewModel.class); to a variable of the base type ViewModel, so you will only be able to access methods available in ViewModel.

Replace private ViewModel mViewModel; with private MovieViewModel mViewModel;

Sign up to request clarification or add additional context in comments.

Comments

1

private ViewModel mViewModel;

ViewModel doesn't have getMovieList, so change that to

private MovieViewModel viewModel;

Comments

1

Your mViewModel is of type ViewModel, which has no method called getMovieList. Change the type to MovieViewModel.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.