Search code examples
androidandroid-viewmodel

Android - Unable to call methods defined in ViewModel


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'


Solution

  • private ViewModel mViewModel;

    ViewModel doesn't have getMovieList, so change that to

    private MovieViewModel viewModel;