How to dynamically query the room database at runtime?

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

The problem

Is it possible construct a query at runtime?


Use case

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


        
8条回答
  •  猫巷女王i
    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> getUsers(SupportSQLiteQuery query);
         }
    

    Usage:

         LiveData> 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

提交回复
热议问题