enable to use tomtom search api in kotlin

244 Views Asked by At

Been searching for a week now, The official documentation are not clear at all.

as mentioned there, the code

val searchServiceConnection = SearchServiceManager.createAndBind(context,
    searchServiceConnectionCallback)

should initialize the search API in the application. but it is not clear how to use it after this.

I installed and initialized the API in the proper way :

Gradle:

//library required for search
implementation("com.tomtom.online:sdk-search:2.4264")



android {
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

AndroidManifest

<meta-data
            android:name="OnlineSearch.Key"
            android:value="your-tomtom-key" />
2

There are 2 best solutions below

0
On BEST ANSWER

I assume that you have a proper API key inside the AndroidManifest.xml file. Given above you can start playing with TomTom Search API in three steps:

  1. Create the SearchAPI object:

    val searchApi = OnlineSearchApi.create(applicationContext)!!
    
  2. Create the Search query object:

    val text = "Berlin"
    val searchQuery = FuzzySearchQueryBuilder.create(text).build()
    
  3. Call Search API and catch the results inside a listener:

    searchApi.search(searchQuery, object: FuzzySearchResultListener {
        override fun onSearchResult(response: FuzzySearchResponse?) {
            Toast.makeText(applicationContext, "results", Toast.LENGTH_SHORT).show()
        }
    
        override fun onSearchError(error: SearchError?) {
            Toast.makeText(applicationContext, "error", Toast.LENGTH_SHORT).show()
        }
    })
    
0
On

Based on the given answer, that is now deprecated, here is the new equivalent:

    private val searchApi = OnlineSearchApi.create(application, TOMTOM_API_KEY)

    val term = "Berlin"
    
    searchApi.search(FuzzySearchSpecification.Builder(term).build(), object : FuzzyOutcomeCallback {
                        override fun onError(error: SearchException) {
                            Log.e(TAG, "onError: ", error)
                        }
            
                        override fun onSuccess(fuzzyOutcome: FuzzyOutcome) {
                            for (fuzzyDetails in fuzzyOutcome.fuzzyDetailsList)
                                fuzzyDetails.apply { // process results (here we just print them)                               
                                  Log.d(TAG, "onSuccess: fuzzyDetails = $fuzzyDetails")
                                }
                              }
                            })