Build an InstantSearch Android page from an empty Android project.
This guide walks you through the steps needed to create a full InstantSearch Android experience from scratch.This guide walks you through the steps needed to create a full InstantSearch Android experience from scratch.It includes:
To use InstantSearch, you need an Algolia account.
Sign up for a new account or use the following credentials
(which include a pre-loaded dataset of products appropriate for this guide):
The central part of your search experience is the Searcher.
The Searcher performs a and obtains search results.
Most InstantSearch components connected to the Searcher.In this guide, you’ll only target one index, so instantiate a HitsSearcher with the proper credentials.Go to MyViewModel.kt file and add the following code:
Kotlin
Report incorrect code
Copy
class MyViewModel : ViewModel() { val searcher = HitsSearcher( applicationID = "latency", apiKey = "1f6fd3a6fb973cb08419fe7d288fa4db", indexName = "instant_search" ) override fun onCleared() { super.onCleared() searcher.cancel() }}
A ViewModel is a good place to put your data sources. This way, the data persists during orientation changes and you can share it across multiple fragments.
Suppose you want to display search results in a RecyclerView.
To simultaneously provide a good user experience and display thousands of products,
you can implement an infinite scrolling mechanism using the Paging Library from Android Architecture Component.To display your results:
1
Create the data source
Create a LiveData object, which holds a PagedList of Product.
Create the Product data class which contains a single name field.
Kotlin
Report incorrect code
Copy
@Serializabledata class Product( val name: String)
In the ProductFragment, get a reference of MyViewModel using activityViewModels().
Then, observe the LiveData to update the ProductAdapter on every new page of products.
Finally, configure the RecyclerView by setting its adapter and LayoutManager.
Kotlin
Report incorrect code
Copy
class ProductFragment : Fragment(R.layout.fragment_product) { private val viewModel: MyViewModel by activityViewModels() private val connection = ConnectionHandler() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val adapterProduct = ProductAdapter() viewModel.paginator.liveData.observe(viewLifecycleOwner) { pagingData -> adapterProduct.submitData(lifecycle, pagingData) } view.findViewById<RecyclerView>(R.id.productList).let { it.itemAnimator = null it.adapter = adapterProduct it.layoutManager = LinearLayoutManager(requireContext()) it.autoScrollToStart(adapterProduct) } } override fun onDestroyView() { super.onDestroyView() connection.clear() }}
To display the ProductFragment, update activity_main.xml to have a container for the fragments:
To search your data, users need an input field. Any change in this field should trigger a new request, and then update the search results.To achieve this, use a SearchBoxConnector. This takes a Searcher and connected to Pagiantor using connectPaginator.
Kotlin
Report incorrect code
Copy
class MyViewModel : ViewModel() { // Searcher initialization // Hits initialization // ... val searchBox = SearchBoxConnector(searcher) val connection = ConnectionHandler(searchBox) init { connection += searchBox.connectPaginator(paginator) } override fun onCleared() { super.onCleared() searcher.cancel() connection.clear() }}
Most InstantSearch components should be connected and disconnected in accordance to the Android Lifecycle to avoid memory leaks.
A ConnectionHandler handles a set of Connection s for you: Each += call with a component implementing the Connection interface will connect it and make it active. Whenever you want to free resources or deactivate a component, call the disconnect method.
Connect the SearchBoxViewAppCompat to the SearchBoxConnectorPagedList stored in MyViewModel using a new ConnectionHandler that conforms to the ProductFragment lifecycle:
Kotlin
Report incorrect code
Copy
class ProductFragment : Fragment(R.layout.fragment_product) { private val viewModel: MyViewModel by activityViewModels() private val connection = ConnectionHandler() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // Hits // ... val searchBoxView = SearchBoxViewAppCompat(searchView) connection += viewModel.searchBox.connectView(searchBoxView) } override fun onDestroyView() { super.onDestroyView() connection.clear() }}
You can now build and run your app, and see a basic search experience. The results change with each key stroke.
It’s a good practice to show the number of hits that were returned for a search. You can use the Stats components to do this with minimal code.Add a StatsConnector to your MyViewModel, and connect it with a ConnectionHandler.
Kotlin
Report incorrect code
Copy
class MyViewModel : ViewModel() { // Searcher initialization // Hits initialization // SearchBox initialization // ... val stats = StatsConnector(searcher) val connection = ConnectionHandler(searchBox, stats) override fun onCleared() { super.onCleared() searcher.cancel() connection.clear() }}
Add a TextView to your product_fragment.xml file to display the stats.
Filtering search results helps your users find what they want. You can create a FacetList to filter products by category.Create a drawable resource ic_check.xml. This resource displays checked filters.
You can use a new component to handle the filtering logic: the FilterState.Pass the FilterState to your FacetListConnector. The FacetListConnector needs an attribute: you should use "categories".
Inject MyFacetListViewHolder.Factory into your FacetListAdapter. The FacetListAdapter is an out of the box RecyclerView.Adapter for a FacetList.Connect the different parts together:
The Searcher connects itself to the FilterState, and applies its filters with every search.
The FilterState connects to your products Paginator to invalidate search results when new filter are applied.
Add displayFilters and navigateToFilters() to MyViewModel to trigger filters display:
Kotlin
Report incorrect code
Copy
class MyViewModel : ViewModel() { // Client, Searcher... // Products // Stats // FilterState // ... private val _displayFilters = MutableLiveData<Unit>() val displayFilters: LiveData<Unit> get() = _displayFilters fun navigateToFilters() { _displayFilters.value = Unit } override fun onCleared() { super.onCleared() searcher.cancel() connection.clear() }}
In ProductFragment, add a listener to the filters button to switch to FacetFragment:
Kotlin
Report incorrect code
Copy
class ProductFragment : Fragment() { private val connection = ConnectionHandler() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.product_fragment, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val viewModel = ViewModelProvider(requireActivity())[MyViewModel::class.java] // Hits // SearchBox // Stats // ... view.findViewById<Button>(R.id.filters).setOnClickListener { viewModel.navigateToFilters() } } override fun onDestroyView() { super.onDestroyView() connection.clear() }}
Add navigation setup to display FacetFragment:
Kotlin
Report incorrect code
Copy
class MainActivity : AppCompatActivity() { val viewModel: MyViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_getting_started) showProductFragment() setupNavigation() } private fun showProductFragment() { supportFragmentManager.commit { replace<ProductFragment>(R.id.container) } } private fun setupNavigation() { viewModel.displayFilters.observe(this) { showFacetFragment() } } private fun showFacetFragment() { supportFragmentManager.commit { add<FacetFragment>(R.id.container) addToBackStack("facet") } } override fun onSupportNavigateUp(): Boolean { if (supportFragmentManager.popBackStackImmediate()) return true return super.onSupportNavigateUp() }}
You can now build and run your app to see your advanced search experience.
This experience helps your users to filter search results and find what they’re looking for.
Highlighting enhances the user experience by putting emphasis on the parts of the result that match the .
It’s a visual indication of why a result is relevant to the query.You can add highlighting by implementing the Highlightable interface on Product.
Define a highlightedName field to retrieve the highlighted value for the name attribute.
Kotlin
Report incorrect code
Copy
@Serializabledata class Product( val name: String, override val _highlightResult: JsonObject?) : Highlightable { public val highlightedName: HighlightedString? get() = getHighlight("name")}
Use the .toSpannedString() extension function to convert an HighlightedString into a SpannedString that can be assigned to a TextView to display the highlighted names.
Kotlin
Report incorrect code
Copy
class ProductViewHolder(view: View) : RecyclerView.ViewHolder(view) { private val itemName = view.findViewById<TextView>(R.id.itemName) fun bind(product: Product) { itemName.text = product.highlightedName?.toSpannedString() ?: product.name }}
You now have a fully working search experience: your users can search for products, refine their results, and understand the number of returned and why they’re relevant to the query.Find the full source code in GitHub.