API Reference / Android Widgets / Hits
Apr. 24, 2019

About this widget

Hits is a view with helper components used to display a list of search results.

Read about HitsPaging if you want to use the infinite scroll pattern in your search.

To add Hits to your search experience, use these components:

  • Searcher: The Searcher that handles your searches.
  • T: A data class representing a search result.
  • HitsView<T>: The view that will render objects of type T.

Examples

You can use deserialize to convert raw hits into your own data class using the Serializable annotation.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class MyActivity : AppCompatActivity() {

    val client = ClientSearch(
        ApplicationID("YourApplicationID"),
        APIKey("YourAPIKey")
    )
    val index = client.initIndex(IndexName("YourIndexName"))
    val searcher = SearcherSingleIndex(index)
    val connection = ConnectionHandler()
    val adapter = MovieAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        connection += searcher.connectHitsView(adapter) { response ->
            response.hits.deserialize(Movie.serializer())
        }
        searcher.searchAsync()
    }

    override fun onDestroy() {
        super.onDestroy()
        connection.disconnect()
        searcher.cancel()
    }
}

@Serializable
data class Movie(
    val title: String
)

class MovieViewHolder(val view: TextView): RecyclerView.ViewHolder(view) {

    fun bind(data: Movie) {
        view.text = data.title
    }
}

class MovieAdapter : RecyclerView.Adapter<MovieViewHolder>(), HitsView<Movie> {

    private var movies: List<Movie> = listOf()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder {
        return MovieViewHolder(TextView(parent.context))
    }

    override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
        val movie = movies[position]

        holder.bind(movie)
    }

    override fun setHits(hits: List<Movie>) {
        movies = hits
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return movies.size
    }
}

Parameters

transform
type: (ResponseSearch) -> List<T>
Required

A function transforming the search response into a list of results of your class T.

1
2
3
4
val transform: (ResponseSearch) -> List<Movie> = { response ->
    response.hits.map { hit -> Movie(hit.json.getPrimitive("title").content) }
}
searcher.connectHitsView(adapter, transform)

Did you find this page helpful?