简体   繁体   中英

How to change the order of a LiveData List?

I'm trying to change the order in which the wrestlers are displayed in my RecyclerView. I want to give the user the option displaying the list by first name in Ascending, Descending, and Random order. How can I change the order of the items in the LiveData list?

The list of Wrestlers is stored in a Room Database, I query the database for all the wrestlers in ascending order by default.

WrestlersDao

    @Query("SELECT * FROM wrestler_table WHERE ORDER BY mFirstName :sortOrder 
    LIMIT :size")
    LiveData<List<WrestlersEntity>> getAllWrestlers(int size, String sortOrder);

MainActivityViewModel

private LiveData<List<WrestlersEntity>> mWrestlersList;

The mWrestlersList is displayed in my RecyclerView.

MainActivity

mMainActivityViewModel.getWrestlersList().observe(this, wrestlersEntities -> {
    adapter.submitList(wrestlersEntities);
});

I was thinking I could Query the Database again, would I have to create a new query in the DAO to change the order of the LiveData List, I'm not sure if there is a way to change the ASC programmatically in the original query.

The other option that sounds like it might work is to use a Transformation.map, but I'm struggling to understand this concept.

MainActivityViewModel

Transformations.map(mWrestlersList) {
    Collections.shuffle((List<?>) mWrestlersList);
}

Any help here would be greatly appreciated.

Pass the column-name and sort-order as parameters; eg. for sorted pagination:

// getAllWrestlers("mFirstName", "ASC", 50, 0);
@Query("SELECT * FROM wrestler_table ORDER BY :columnName :sortOrder LIMIT :limit OFFSET :offset")
LiveData<List<WrestlersEntity>> getAllWrestlers(String columnName, String sortOrder, int limit, int offset);

Because unless passing them as parameters, one cannot really control the result-window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM