简体   繁体   中英

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.

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

Try to change the & to AND and add parentheses to separate the OR s:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM