In Android Room how can I create and call a custom query
If you are using MVVM architecture with LiveData follow this method.
1. Observe the LiveData List in MoviesActivity.java
final LiveData<List<MoviesData>> viewModelData = moviesViewModel.getMoviesByGenre("comedy");
viewModelData.observe(this, new Observer<List<MoviesData>>() {
@Override
public void onChanged(List<MoviesData> moviesData) {
//Handle the Movies List here.
}
});
2. In MoviesViewModel.java
public LiveData<List<NotificationData>> getMoviesByGenre(String genere) {
MoviesRepository mRepository = new MoviesRepository(application);
LiveData<List<MoviesData>> mMoviesData = mRepository.getMoviesByGenre(genere);
return mMoviesData;
}
3. MoviesRepository.java
private MoviesDao mMoviesDao;
//Initialize.
AppDatabase db = AppDatabase.getAppDatabase(application);
mMoviesDao = db.moviesDao();
public LiveData<List<MoviesData>> getMoviesByGenre(String genere) {
mMovies = mMoviesDao.findMovieByGenre(genere);
return mMovies;
}
3. In MoviesDao
@Query("SELECT * FROM movie_table ORDER BY genre")
public LiveData<List<Movies> findMovieByGenre(String genre);
So you can Observe query result in your Activity class' Observe method.