How to add google places autocomplete in Android Edittext?

Please Share On:

This article will show you how can you implement google places API in your app. Google made an autocomplete places API, which makes it easier to select an address and also gives a suggestion when you start typing.

Let’s begin with how to implement google places API in your app. Here are the shortlists of step I am going to explain:

  1. Google Developer Console
  2. Strings.xml
  3. XML File
  4. Java Code
  5. Output

1) Google Developer Console

Here, you have to enable Google Places API and create credentials. Lets begin.

1.1) login

First, login to your google developer console. Click on “Credentials” on the left-hand sidebar.

credentials

1.2) CREATE CREDENTIALS

Now, add your new credential for your project by clicking “CREATE CREDENTIALS“. After that click on the edit button to change your API credential name and restriction mode and save your API credential.

You also need to add your package name and SHA-1 fingerprint. You can find package name on the top of your each java file.

package com.elsebazaar.googleplaces;

SHA-1 fingerprint can be found in your project. Go to Gradle ->Your Project Name ->Tasks ->Android ->signingReport. Check your project log, your project SHA-1 fingerprint is there.

1.3) Enable Google Places API

Go to Library -> Place API and enable your Google Places API.

places api

1.4) Copy API Key

You have to use your API key in your project. To get your API key, go back to credential again and select your app credential. You will see an API KEY located on the right-hand side. Copy your API key for now.

API key



2) String.xml

Create a resource of your API key and paste the above API key value in “Your_API_KEY”.

<resources>
    <string name="api_key">Your_API_KEY</string>
</resources>

3) XML File

Create your .xml file with one edittext. An example is shown below.

<EditText
        android:id="@+id/etaddress"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:textColor="@color/black"
        android:autofillHints="@string/hint_address"
        android:hint="@string/hint_address"
        android:ems="10"
        android:inputType="textPostalAddress"
        android:layout_weight="1"/>


4) Java Code

Implement two libraries in your project gradle

implementation 'com.google.android.gms:play-services-location:17.1.0'
    implementation 'com.google.android.libraries.places:places:2.4.0'

4.1) Initialize edittext

EditText maddress;

4.2) Assign edittext

maddress = findViewById(R.id.etaddress);

4.3) Initialize Places

String apiKey = getString(R.string.api_key);
        if (!Places.isInitialized()) {
            Places.initialize(getApplicationContext(), apiKey);
        }

4.4) edittext setOnClickListerner

//maddress on clicklistener
        maddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 // Set the fields to specify which types of place data to
                // return after the user has made a selection.
                List<Place.Field> field = Arrays.asList(Place.Field.ID, Place.Field.ADDRESS);

                // Start the autocomplete intent.
                Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, field)
                        .build(Address.this);
                //start activity result
                startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

            }
        });

4.5) Result Activity

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                //When success initialize place
                Place place = Autocomplete.getPlaceFromIntent(data);
               
                //set address on edittext
                maddress.setText(place.getAddress());
            } else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
                // TODO: Handle the error.
                Status status = Autocomplete.getStatusFromIntent(data);
                //Log.i(TAG, status.getStatusMessage());
            } else if (resultCode == RESULT_CANCELED) {
                // The user canceled the operation.
            }
        }
    }

5) Output

Run your program and see the output




You may interest on the following topics:

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright @2023. All Right Reserved.


Social media & sharing icons powered by UltimatelySocial