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 its 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)

Getting started with Mani, what3words Android Developer:

1
2

Installation

The artifact is available through Maven Central .

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

Usage

Take a look at Github for samples of how to use the component and some of its 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

ReplaceYOUR_API_KEY_HERE with your what3words API key.

For eachsuggestion it is possible to obtain the 3 word address (words ) and other characteristics such ascountry ,latitude andlongitude (ifreturnCoordinates 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.

Parameter Default value Type Description XML Programatically
apiKey N/A string Your what3words API key. (mandatory) Yes
hint e.g. lock.spout.radar String Placeholder text to display in the input in its default empty state. Yes Yes
errorMessage An error occurred. Please try again later String Overwrite the generic error message with a custom value. Yes Yes
invalidAddressMessage No valid what3words address found String Overwrite the validation error message with a custom value. Yes Yes
focus N/A Coordinates This 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
clipToCountry N/A String Clip results to a given country or comma separated list of countries. Example value:"GB,US". Yes
clipToCircle N/A Coordinates, Int Clip results to a circle, specified by Coordinate(lat,lng) and kilometres, where kilometres in the radius of the circle. Yes
clipToBoundingBox N/A BoundingBox Clip results to a bounding box specified using co-ordinates. Yes
clipToPolygon N/A List of Coordinates Clip results to a bounding box specified using co-ordinates. Yes
allowInvalid3wa false Boolean By 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
returnCoordinates false Boolean Calls 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) Yes Yes
displayUnit DisplayUnits.SYSTEM DisplayUnits Set end-user display unit, DisplayUnits.SYSTEM (default), DisplayUnits.METRIC, DisplayUnits.IMPERIAL Yes Yes
allowFlexibleDelimiters false Boolean Allow EditText to accept different delimiters than the what3words standard full stop "index.home.raft", i.e "index home raft" or "index,home,raft". Yes Yes

Voice properties:

Property Default value Type Description XML Programatically
voiceEnabled false Boolean Enables voice suggestion to allow the user to say the three word address instead of writing it. Yes Yes
voiceLanguage en String Available 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 Korean Yes Yes
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
Mobile App Add a 3 word address input field Android Java

Related tutorials