Search code examples
androidandroid-sqliteandroid-roomandroid-sql

Android SQLite dynamically insert sorting (ASD or DESC), is it possible?


I'm trying to use one method for dao (Room) to get items by a specific sorting dynamically, but compiler gives an error for the next SQL query

enter image description here

enter image description here

So it's not possible? Do I have to create duplicate methods with different sorting?


Solution

  • you can not perform if and else logic in the sqlite query

    You should use @RawQuery like this:

     @Dao
     interface RawDao {
       @RawQuery
       fun getTestItems(SupportSQLiteQuery query): DataSource.Factory
     }
    
     // Usage of RawDao
     // for example set: restOfQuery = sortBy + "ASC"
     val query = SimpleSQLiteQuery(
         "SELECT * FROM Items ORDER BY ?",
         new Object[]{ restOfQuery }); 
     val result = rawDao.getTestItems(query);
    

    Or another way is that you use multiple functions for multiple orderings.