Dynamic Order By using Room

穿精又带淫゛_ 提交于 2019-12-23 03:17:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!