Room user configurable order by queries

前端 未结 4 650
误落风尘
误落风尘 2021-01-11 09:00

I am migrating an app to use Room from normal Sqlite and one part that I am having trouble with is that there are several queries that have an orde

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-11 09:40

    As tyczj already suggested you can us a RawQuery. In addition, the SimpleSQLiteQuery can also be moved into the DAO so there are no SQL statements outside of the DAO.

    A DAO can also be defined via an abstract class. This allows you to add a method which executes the SimpleSQLiteQuery.

    Example:

    @DAO
    public abstract class UserDao {
    
        @RawQuery
        public abstract List getUsersViaRawQuery(SupportSQLiteQuery query);
    
        public List getUsersOrderBy(String column) {
            String statement = "SELECT * FROM user ORDER BY " + column + " ASC";
            SupportSQLiteQuery query = new SimpleSQLiteQuery(statement, new Object[]{});
            return getUsersViaRawQuery(query);
        }
    
    }
    

    The column parameter could also be replaced by an enum, which only allows specific values.

    Example:

    private static String createOrderByString(Order order) {
        switch (order) {
            case NAME:
                return "ORDER BY first_name ASC, last_name ASC";
            case AGE:
                return "ORDER BY age DESC";
            default:
                return "";
        }
    }
    

提交回复
热议问题