Android SearchSuggestSelection enable query startswith instead of contains search
-
11-12-2019 - |
Question
I'm using the Android SearchRecentSuggestionsProvider and Searchable Configuration to display previous in app searches and would like to limit the suggested responses to only return enteries that start with ? (what the user is typing)
currently "p" returns phone, ipod, photo, happy, and what I'm after is just phone and photo
Something eqlivent to SQL like % but I can't seem to get that to work.
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:hint="@string/product_search_hint"
android:imeOptions="actionSearch"
android:label="@string/app_label"
android:searchSuggestAuthority="com.myapp.ProductSearchSuggestionProvider"
android:searchSuggestSelection="word MATCH ?" >
</searchable>
Tried:
android:searchSuggestSelection="WORD LIKE '%'?"
Solution
If you were implementing a fully custom suggestion provider, applying customizations at this level would work as expected. However, under the covers, SearchRecentSuggestionsProvider queries its local table with the following hard-coded arguments (have a look):
- selection = "display1 LIKE ?"
- selectionArgs = ["%{query}%"]
where {query} is the search query (it is sandwiched between two percent signs so that any character match anywhere in the string counts). It ignores the value passed in for the selection string (which is what you are setting with the searchSuggestSelection
parameter) and the args array (beyond checking if it is empty), so there really isn't much you can do from XML.
Because the implementation ignores incoming parameters, there is no easy fix or override. To save yourself duplicate coding, I would:
- Copy the entire implementation of
SearchRecentSuggestionsProvider
from the link above. Nothing the class does should be framework private, so a direct copy should compile. - Modify the construction statement from the args array, inside the
query()
method, to beString like = selectionArgs[0] + "%"
instead ofString like = "%" + selectionArgs[0] + "%"
(i.e. remove the first percent) - Subclass
ProductSearchSuggestionProvider
from your new implementation instead.
OTHER TIPS
Have you tried string concatenation?
word LIKE ? || '%'
||
is string concatenation in SQLite.