问题
I want to create a dynamic query using room so that in one case the query returns a particular order type and during runtime if the order type changes then a new query is created and the data is returned ordered according to this type.
I am returning a DataSource.Factory object using Room. I am using the below statement to process my query:-
if(getSortOrderType().equals(context.getString(R.string.sortByPopular))) {
dbSortType = "popularity";
} else {
dbSortType = "vote_average";
}
movieLiveData =
new LivePagedListBuilder<>(MovieDatabase
.getMovieDbInstance(context)
.getMovieDao().getAllMovies(new
SimpleSQLiteQuery("SELECT * FROM main_movie ORDER BY ? DESC",
new Object[]{dbSortType})), config)
.setBoundaryCallback(movieModelBoundaryCallback)
.build();
But, during runtime I see that the data being returned is ordered by the already set Primary Key i.e id and not according to this type that I am constructing in the above statement.
How to use the statement to return the result sorted by the sort type selected.
The Dao method used is:-
@RawQuery(observedEntities = MovieModel.class)
DataSource.Factory<Integer,MovieModel> getAllMovies(SupportSQLiteQuery query);
回答1:
Okay so, I have found a simple answer to that.
I just replaced the statement --
new SimpleSQLiteQuery("SELECT * FROM main_movie ORDER BY ? DESC", new Object[]{dbSortType})
to this:-
new SimpleSQLiteQuery("SELECT * FROM main_movie ORDER BY "+ dbSortType + " DESC"))
来源:https://stackoverflow.com/questions/51347990/dynamic-order-by-using-room