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

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


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.


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();


  • problem

if you make a query like this,

"SELECT * FROM Association WHERE memberStatus = " + Association.MEMBER_STATUS_APPROVED

it's just

"SELECT * FROM Association WHERE memberStatus = somevalue"

sql cannot know "somvalue" is a string.


  • try this (wrap it with quotation mark)

"SELECT * FROM Association WHERE memberStatus = '" + Association.MEMBER_STATUS_APPROVED + "'"