How to dynamically query the room database at runtime?

后端 未结 8 1779
青春惊慌失措
青春惊慌失措 2020-11-30 05:42

The problem

Is it possible construct a query at runtime?


Use case

@Query(\"SELECT * FROM playlist \" +
        \"WHERE play         


        
相关标签:
8条回答
  • 2020-11-30 06:21

    Use SupportSQLiteQuery.

    https://developer.android.com/reference/android/arch/persistence/db/SupportSQLiteQuery

    Latest release 1.1.1 now uses SupportSQLiteQuery.

    A query with typed bindings. It is better to use this API instead of rawQuery(String, String[]) because it allows binding type safe parameters.

    @Dao
         interface RawDao {
             @RawQuery(observedEntities = User.class)
             LiveData<List<User>> getUsers(SupportSQLiteQuery query);
         }
    

    Usage:

         LiveData<List<User>> liveUsers = rawDao.getUsers( new 
    SimpleSQLiteQuery("SELECT * FROM User ORDER BY name DESC"));
    

    Update your gradle to 1.1.1

    implementation 'android.arch.persistence.room:runtime:1.1.1'
    implementation 'android.arch.lifecycle:extensions:1.1.1'
    annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
    

    Note: if you upgrade to 1.1.1, and are using String instead of SupportSQLiteQuery,

    you will get the error:

    RawQuery does not allow passing a string anymore. Please use android.arch.persistence.db.SupportSQLiteQuery.

    Using SupportSQLiteQuery as above will solve the problem.

    Note: Make sure you pass in SupportSQLiteQuery query parameter or you will get this error:

    RawQuery methods should have 1 and only 1 parameter with type String or SupportSQLiteQuery

    0 讨论(0)
  • 2020-11-30 06:21
      @Query("select * from task where state = :states and sentdate between :fromdate and :todate")
      List<Task> getFilterAll(String states, String fromdate, String todate);
    

    Here we need to use column name state. Whenever need to achieve custom query just pass the value through the parameter from the activity or fragement will get in to the interface we will apply inside the query. like example in the above code (:fromdate, :todate)

    Colon is must. Which parameter you will going to use inside the query we will mention before start with : symbol.

    0 讨论(0)
提交回复
热议问题