Raunit Verma
Raunit Verma

Reputation: 196

Android Room Database like query not working

I have added a field to know whether the item is deleted or not by the user and if it is deleted it should not be visible to the user.

I wrote the following query for it

 @Query("SELECT * FROM post_info WHERE deleted=0 & postedBy LIKE :search || '%' OR  postName LIKE :search || '%' OR postDes LIKE :search || '%' ORDER BY postid DESC ")
     fun searchFilter(search:String):Flow<List<PostEntity>>

But i am getting all the data and not only WHERE deleted=0 means false but when I search and filter it manually it works fine like

  viewModel.searchFilter(searchQuery).observe(this) {

            it.let {
                var listOF= mutableListOf<PostEntity>()
                for(list in it){
                    if(!list.deleted){
                        listOF.add(list)

                    }
                }
                adapter.setDataList(listOF)}
        }

This works fine but the Query doesn't work.

Upvotes: 1

Views: 1540

Answers (2)

Shailendra Madda
Shailendra Madda

Reputation: 21531

Like query will work with this syntax:

inputValue LIKE '%' || :fieldToMatch || '%'

& should be replaced with AND

Replace this:

@Query("SELECT * FROM post_info WHERE deleted=0 & postedBy LIKE :search || '%' OR  postName LIKE :search || '%' OR postDes LIKE :search || '%' ORDER BY postid DESC ")
fun searchFilter(search:String):Flow<List<PostEntity>>

With this:

@Query("SELECT * FROM post_info WHERE deleted=0 AND (postedBy LIKE '%' || :search || '%' OR  postName LIKE '%' || :search || '%' OR postDes LIKE '%' || :search || '%') ORDER BY postid DESC ")
fun searchFilter(search:String): Flow<List<PostEntity>>

Upvotes: 3

lpizzinidev
lpizzinidev

Reputation: 13289

Try to change the & to AND and add parentheses to separate the ORs:

@Query("SELECT * FROM post_info WHERE deleted=0 AND (postedBy LIKE :search || '%' OR  postName LIKE :search || '%' OR postDes LIKE :search || '%') ORDER BY postid DESC ")
fun searchFilter(search:String):Flow<List<PostEntity>>

Upvotes: 1

Related Questions