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.

Full sample apps for the component can be found in our Github repo
github icon white Android Sample Apps

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)

Getting started with Mani, what3words Android Developer:

1Get API key
Signup to create key
2Installation

The artifact is available through Maven Central.

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

Take a look at this repository for samples of how to use the component and some of its more advanced features.

github icon white Android Component

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

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)

	suggestionEditText.apiKey("YOUR_API_KEY_HERE")
            .returnCoordinates(false)
            .onSuggestionSelected { suggestion ->
                if (suggestion != null) {
                    Log.i( "MainActivity","words: ${suggestion.words}, country: ${suggestion.country}, distance: ${suggestion.distanceToFocusKm}, near: ${suggestion.nearestPlace}, latitude: ${suggestion.coordinates?.lat}, longitude: ${suggestion.coordinates?.lng}")
                } else {
                    Log.i("MainActivity", "invalid w3w address")
                }
            }
            .onError { error ->
                Log.e("MainActivity", "${error.key} - ${error.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.YesYes
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/AList of Coordinates Clip results to a bounding box specified using co-ordinates.Yes
allowInvalid3wafalseBooleanBy default the EditText field will clear an inputted value if a valid 3 word address is not entered. Setting allowInvalid3wa to true stops this behaviour and the value is persisted in the EditText.Yes
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
displayUnitDisplayUnits.SYSTEMDisplayUnitsSet end-user display unit, DisplayUnits.SYSTEM (default), DisplayUnits.METRIC, DisplayUnits.IMPERIALYesYes
allowFlexibleDelimitersfalseBooleanAllow EditText to accept different delimiters than the what3words standard full stop "index.home.raft", i.e "index home raft" or "index,home,raft".YesYes

Voice properties:

PropertyDefault valueTypeDescriptionXMLProgramatically
voiceEnabledfalseBooleanEnables voice suggestion to allow the user to say the three word address instead of writing it.YesYes
voiceLangaugeenStringAvailable 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
4Styling

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
5Troubleshooting

If you encounter errors or issues related to convert-to-coordinate requests while using the Free plan, please check the network panel for the following error message Error 402 payment required and its response, indicating the need to upgrade to a higher plan:

{
    "error": {
        "code": "QuotaExceeded",
        "message": "Quota Exceeded. Please upgrade your usage plan, or contact support@what3words.com"
    }
}
Copied

For more information, visit our API plans page. If you need further assistance, contact support@what3words.com.

Mobile AppAdd a 3 word address input fieldAndroidJava

Related tutorials