> For the complete documentation index, see [llms.txt](https://docs.mapbox.com/android/ja/search/llms.txt)

# Search history

**Search history** is a list of the most recent search results selected on a device. Technically, it's a predefined type of [Data Provider](https://docs.mapbox.com/android/ja/search/guides/search-engine/data-providers/) that stores [`HistoryRecord`](https://docs.mapbox.com/android/search/api/core/2.28.2/sdk/com.mapbox.search.record/-history-record/).

## Working with search history

Search history is available via [`HistoryDataProvider`](https://docs.mapbox.com/android/search/api/core/2.28.2/sdk/com.mapbox.search.record/-history-data-provider/) which can be obtained from the [`ServiceProvider.historyDataProvider`](https://docs.mapbox.com/android/search/api/core/2.28.2/sdk/com.mapbox.search/-service-provider/history-data-provider.html):

```kotlin
val historyDataProvider = ServiceProvider.INSTANCE.historyDataProvider()
```

As any other [Data provider](https://docs.mapbox.com/android/ja/search/guides/search-engine/data-providers/), `HistoryDataProvider` gives the API to read or change search history entries.

> **Related content (example): [Search history](https://docs.mapbox.com/android/ja/search/examples/history/)**
> 
> Learn how to access all saved search history records.

### `SearchEngine` with `HistoryDataProvider`

If a user has searched in your app before, [`SearchEngine`](https://docs.mapbox.com/android/search/api/core/2.28.2/sdk/com.mapbox.search/-search-engine/) with attached `HistoryDataProvider` will suggest results from their search history that match the query.

If a `SearchEngine` instance is created via [`SearchEngine.createSearchEngineWithBuiltInDataProviders()`](https://docs.mapbox.com/android/search/api/core/2.28.2/sdk/com.mapbox.search/-search-engine/-companion/create-search-engine-with-built-in-data-providers.html), the `HistoryDataProvider` is already attached to the `SearchEngine`. Otherwise, `HistoryDataProvider` can be attached later:

```kotlin
val searchEngine = SearchEngine.createSearchEngine(
    SearchEngineSettings(getString(R.string.mapbox_access_token))
)

val registerTask = searchEngine.registerDataProvider(
    ServiceProvider.INSTANCE.historyDataProvider(),
    object : CompletionCallback<Unit> {
        override fun onComplete(result: Unit) {
            Log.i("SearchApiExample", "History data provider has been attached")
        }

        override fun onError(e: Exception) {
            Log.i("SearchApiExample", "Unable to attach history data provider", e)
        }
    }
)
```

The `SearchEngine` automatically adds to a user's history every time a single suggestion is selected with [`SearchEngine.select(suggestion: SearchSuggestion, ...)`](https://docs.mapbox.com/android/search/api/core/2.28.2/sdk/com.mapbox.search/-search-engine/select.html):

```kotlin
fun processSuggestions(suggestions: List<SearchSuggestion>) {
    val suggestion: SearchSuggestion = pickSuggestion()
    val selectionTask = searchEngine.select(suggestion, object : SearchSelectionCallback {
        override fun onSuggestions(suggestions: List<SearchSuggestion>, responseInfo: ResponseInfo) {
            // ...
        }

        override fun onResult(
            suggestion: SearchSuggestion, 
            result: SearchResult, 
            responseInfo: ResponseInfo,
        ) {
            // Resolved result was added to `HistoryDataProvider`
            // ...
        }

        override fun onResults(
            suggestion: SearchSuggestion,
            results: List<SearchResult>,
            responseInfo: ResponseInfo
        ) {
            // ...
        }

        override fun onError(e: Exception) {
            // ...
        }
    })
}
```

To opt-out saving search result to the search history, provide [`SelectOptions`](https://docs.mapbox.com/android/search/api/core/2.28.2/sdk/com.mapbox.search/-select-options/) with [`addResultToHistory`](https://docs.mapbox.com/android/search/api/core/2.28.2/sdk/com.mapbox.search/-select-options/add-result-to-history.html) set to false:

```kotlin
searchEngine.select(suggestions.first(), SelectOptions(addResultToHistory = false), callback)
```

`SearchEngine` doesn't add anything to the search history in case of reverse geocoding, category search, and when suggestion selection ends with error or category search results. For example when [`SearchSelectionCallback.onResults()`](https://docs.mapbox.com/android/search/api/core/2.28.2/sdk/com.mapbox.search/-search-selection-callback/on-results.html) was called. In this case you can add selected search result to the search history on your own:

```kotlin
private fun addToSearchHistory(searchResult: SearchResult, historyDataProvider: HistoryDataProvider) {
    if (searchResult.indexableRecord is HistoryRecord) {
        // searchResult is a search history entry
        return
    }

    val historyRecord = HistoryRecord(
        id = searchResult.id,
        name = searchResult.name,
        descriptionText = searchResult.descriptionText,
        address = searchResult.address,
        routablePoints = searchResult.routablePoints,
        categories = searchResult.categories,
        makiIcon = searchResult.makiIcon,
        coordinate = searchResult.coordinate,
        type = searchResult.types.first(),
        metadata = searchResult.metadata,
        timestamp = System.currentTimeMillis(),
    )

    val upsertTask = historyDataProvider.upsert(historyRecord, object : CompletionCallback<Unit> {
        override fun onComplete(result: Unit) {
            Log.i("SearchApiExample", "$historyRecord is saved to the search history")
        }

        override fun onError(e: Exception) {
            Log.i("SearchApiExample", "Unable to save $historyRecord to the search history", e)
        }
    })
}
```

## Search history in UI

The [`SearchEngineUiAdapter`](https://docs.mapbox.com/android/ja/search/guides/search-ui/results-view/#searchengineuiadapter) uses search history in the following ways:

-   Show recent searches in its initial state or when [`SearchEngineUiAdapter.search()`](https://docs.mapbox.com/android/search/api/ui/2.28.2/ui/com.mapbox.search.ui.adapter.engines/-search-engine-ui-adapter/search.html) was called with an empty search query.
-   When a user starts to type a query, Search SDK will use the history to populate the suggestions drop down.
-   When a user clicks on a search result, the search result is added to the search history.
-   When a user swipes a recent search record, it is removed from the search history.

Your browser doesn't support HTML5 video. Open [link to the video](https://docs.mapbox.com/android/ja/android/ja/assets/medias/search-history-demo-0c9493e2bad848ed4193ae24af896d19.mp4).