Conditional Display in InstantSearch Android
Handling no results
Not all queries lead to results, and it’s important to let users know when this happens. This gives you an opportunity to provide hints on how to adjust the query. This way, you can ensure users don’t leave your website or search using an external search engine.
Display a message
The easiest way to display a fallback message when a query doesn’t return results is to subscribe to the Searcher
’s response
event and show your “no results” UI whenever the response has no hits
.
1
2
3
4
5
6
7
searcher.response.subscribe {
if (it == null || it.hitsOrNull.isNullOrEmpty()) {
showNoResultsUI()
} else {
hideNoResultsUI()
}
}
Handling the empty query
By default, InstantSearch Android always shows you results, even when the query is empty. Depending on your use case and the way you want to build your UI, you may want to only show results when there’s a query.
To override this behavior, you can implement your own SearchBoxView
. Instead of calling onQueryChanged
or onQuerySubmitted
for every query, you can call them only when the query isn’t empty.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class SearchBoxNoEmptyQuery(
public val searchView: SearchView
) : SearchBoxView {
override var onQueryChanged: Callback<String?>? = null
override var onQuerySubmitted: Callback<String?>? = null
init {
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
query?.isNotEmpty()?.let { onQuerySubmitted?.invoke(query) }
return false
}
override fun onQueryTextChange(query: String?): Boolean {
query?.isNotEmpty()?.let { onQuerySubmitted?.invoke(query) }
return false
}
})
}
override fun setText(text: String?) {
searchView.setQuery(text, false)
}
}
Handling errors
When an error occurs, you might want to display a specific piece of content to help the user go back to a normal state.
To be notified of errors, subscribe to the Searcher
’s error
event.
1
2
3
4
5
searcher.error.subscribe {
if (it != null) {
Log.e("TAG", "Error on search $query: ${it.message}")
}
}