Creating an Android AutoSuggest edittext field with the what3words AutoSuggest Component

easy

The what3words Android AutoSuggest Component provides an easy way of adding a what3words EditText field to an Android app. The component allows the user to enter a 3 word address, providing AutoSuggest suggestions whilst typing and error correction to ensure accurate entries.

The component is straightforward to use and can be configured using a range of properties. The component uses the what3words API or alternatively can be configured to use our Enterprise Suite API Server.

Take a look at Github for samples of how to use the component and some of it’s more advanced features.

Find out how else you can utilise the what3words API in your app by taking a look at the what3words Android API Wrapper.

Minimum supported OS version: 6.0 (API level 23)

 

You will need a what3words API key to complete this tutorial.

2

Installation

The artifact is available through Maven Central.

implementation 'com.what3words:w3w-android-components:2.1.0'
Copied
3

Usage

Take a look at Github for samples of how to use the component and some of it’s more advanced features.

The following should be included in AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yourpackage.yourapp">

    <uses-permission android:name="android.permission.INTERNET" />
Copied

Add the following to build.gradle (app level):

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

add the following ProGuard rules:

-keep class com.what3words.javawrapper.request.* { *; }
-keep class com.what3words.javawrapper.response.* { *; }
-keep class com.what3words.androidwrapper.voice.* { *; } // add if using voice api autosuggest 
Copied

The following should be included in activity_main.xml:

<androidx.constraintlayout.widget.ConstraintLayout 
	  xmlns:android="http://schemas.android.com/apk/res/android"  
	  xmlns:app="http://schemas.android.com/apk/res-auto"  
	  android:layout_width="match_parent"  
	  android:layout_height="match_parent">  
  
	 <com.what3words.components.text.W3WAutoSuggestEditText
		  android:id="@+id/suggestionEditText"  
		  android:layout_width="0dp"  
		  android:layout_height="wrap_content"  
		  app:layout_constraintEnd_toEndOf="parent"  
		  app:layout_constraintStart_toStartOf="parent"  
		  app:layout_constraintTop_toTopOf="parent" />  
		  
</androidx.constraintlayout.widget.ConstraintLayout>
Copied

Adding the component

Replace YOUR_API_KEY_HERE with your what3words API key.

For each suggestion it is possible to obtain the 3 word address (words) and other characteristics such as country, latitude and longitude (if returnCoordinates has been specified).

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

	autoSuggestEditText.apiKey("YOUR_API_KEY_HERE")
            .returnCoordinates(false)
            .onSelected { w3wSuggestion ->
                if (w3wSuggestion != null) {
                    Log.i( "MainActivity","words: ${w3wSuggestion.suggestion.words}, country: ${w3wSuggestion.suggestion.country}, distance: ${w3wSuggestion.suggestion.distanceToFocusKm}, near: ${w3wSuggestion.suggestion.nearestPlace}, latitude: ${w3wSuggestion.coordinates?.lat}, longitude: ${w3wSuggestion.coordinates?.lng}"
                    )
                } else {
                    Log.i("MainActivity", "invalid w3w address")
                }
            }
            .onError {
                Log.e("MainActivity", "${it.key} - ${it.message}")
            }
}
Copied

Enterprise Suite API Server

If you run our Enterprise Suite API Server yourself, you may specify the URL to your own server like so:

autoSuggestEditText.apiKey("YOUR_API_KEY_HERE", "https://api.yourserver.com")  
Copied

Enable voice autosuggest

The component also allows for voice input using the what3words Voice API. This feature allows the user to say 3 words and using speech recognition technology displays 3 word address suggestions to the user.

Before enabling Voice AutoSuggest you will need to add a Voice API plan in your account.

By default the voice language is set to English but this can be changed using the voiceLanguage property (for list of available languages please check the properties table below). Voice input respects the clipping and focus options applied within the general properties. We recommend applying clipping and focus where possible to display as accurate suggestions as possible. To enable voice you can do with programmatically or directly in the XML.

The following should be included in AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.yourpackage.yourapp">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    ...
Copied

The following should be included in activity_main.xml:

 <com.what3words.components.text.W3WAutoSuggestEditText
		  android:id="@+id/suggestionEditText"
		  android:layout_width="0dp"
		  android:layout_height="wrap_content"
		  app:layout_constraintEnd_toEndOf="parent"
		  app:layout_constraintStart_toStartOf="parent"
		  app:layout_constraintTop_toTopOf="parent"
		  app:voiceEnabled="true" />
Copied

or MainActivity.kt / MainActivity.java

 suggestionEditText.apiKey("YOUR_API_KEY_HERE")
	        .returnCoordinates(false)
	        .voiceEnabled(true)
		...
Copied

Advanced usage: properties

There are a range of customisation properties you can use to configure the AutoSuggest Component.

ParameterDefault valueTypeDescriptionXMLProgramatically
apiKeyN/A stringYour what3words API key. (mandatory)Yes
hinte.g. lock.spout.radar StringPlaceholder text to display in the input in its default empty state.Yes
errorMessageAn error occurred. Please try again later StringOverwrite the generic error message with a custom value.YesYes
invalidAddressMessageNo valid what3words address foundStringOverwrite the validation error message with a custom value.YesYes
focusN/A CoordinatesThis is a location, specified as a latitude/longitude (often where the user making the query is). If specified, the results will be weighted to give preference to those near the `focus`Yes
clipToCountryN/A StringClip results to a given country or comma separated list of countries. Example value:"GB,US".Yes
clipToCircleN/A Coordinates, IntClip results to a circle, specified by Coordinate(lat,lng) and kilometres, where kilometres in the radius of the circle. Yes
clipToBoundingBoxN/A BoundingBoxClip results to a bounding box specified using co-ordinates. Yes
clipToPolygonN/A List of Coordinates Clip results to a bounding box specified using co-ordinates.Yes
allowInvalid3wafalseBooleanAllow invalid 3 word addressYes
returnCoordinatesfalseBooleanCalls the what3words API to obtain the coordinates for the selected 3 word address (to then use on a map or pass through to a logistic company, etc) YesYes

Voice properties:

PropertyDefault valueTypeDescriptionXMLProgramatically
voiceEnabledfalse Boolean Enables voice suggestion to allow the user to say the three word address instead of writing it.YesYes
voiceFullscreenfalseBooleanVoice activation will be fullscreen instead of inline.YesYes
voiceLanguageenStringAvailable voice languages: ar for Arabic, cmn for Mandarin Chinese, de for German, en for Global English (default), es for Spanish, hi for Hindi, ja for Japanese and ko for KoreanYesYes
4

Styling

Use our base style as parent and you can set the custom properties available with XML on the table above and the normal EditText styling, i.e:

<style name="YourCustomStyle" parent="Widget.AppCompat.W3WAutoSuggestEditText">
  <item name="android:textColor">#000000</item>
  <item name="android:textColorHint">#888888</item>
  <item name="invalidAddressMessage">Your custom invalid address message</item>
  <item name="errorMessage">Your custom error message</item>
  <item name="android:hint">Your custom placeholder</item>
  <item name="android:textAppearance">@style/YourCustomStyleTextAppearance</item>
</style>

<style name="YourCustomStyleTextAppearance" parent="TextAppearance.AppCompat">
  <item name="android:textSize">22sp</item>
  <item name="android:fontFamily">sans-serif-medium</item>
</style>
Copied

Related tutorials

Back to top