Home > other >  Android Room Database like query not working
Android Room Database like query not working

Time:03-09

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.

CodePudding user response:

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

CodePudding user response:

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>>
  • Related