Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use StringFormat or Constant Variable in android Room Query

I want to query the user associations list with the following room query using public constant variable Association.MEMBER_STATUS_APPROVED.

@Query("SELECT * FROM Association WHERE memberStatus = " + Association.MEMBER_STATUS_APPROVED)
LiveData<List<Association>> loadUserAssociations();

But, room gives me [SQLITE_ERROR] when build. It is possible to re-write that query by replacing the constant variable with parameter like the following.

@Query("SELECT * FROM Association WHERE memberStatus = :statusApproved")
LiveData<List<Association>> loadUserAssociations(String statusApproved);

I would like to know that does Room support such kind of string concatenation or String Format? (or) May be I missing something?

like image 938
Toe Lie Avatar asked Nov 20 '18 05:11

Toe Lie


2 Answers

For those who have the same problem, the following could be the solution in Kotlin:

@Query("SELECT * FROM Association WHERE memberStatus = :statusApproved")
loadUserAssociations(statusApproved: String = Association.MEMBER_STATUS_APPROVED): LiveData<List<Association>>

And I think it is more clean way than hardcoding or passing obvious constant into the function.

like image 187
Sirojiddin Komolov Avatar answered Nov 20 '22 22:11

Sirojiddin Komolov


you can query like below.

Instead of

@Query("SELECT * FROM Association WHERE memberStatus = " + Association.MEMBER_STATUS_APPROVED) LiveData<List<Association>> loadUserAssociations();

use

@Query("SELECT * FROM Association WHERE memberStatus=${Association.MEMBER_STATUS_APPROVED}) LiveData<List<Association>> loadUserAssociations();

like image 1
Varun A M Avatar answered Nov 20 '22 22:11

Varun A M