FIELD NOTES ON BUILDING SYSTEMS

A personal technical publication

Android Google Places Autocomplete feature using new Places SDK

A while back, I wrote a blog on Google Place Autocomplete feature. In that blog, I used Google Play Services version of the Places SDK. However, as of January 29, 2019, the Google Play Services…

A while back, I wrote a blog on Google Place Autocomplete feature. In that blog, I used Google Play Services version of the Places SDK. However, as of January 29, 2019, the Google Play Services version of the Places SDK for Android is deprecated. Google will turn it off by July 29, 2019. Instead of this version of library, Google has now provided a new version of the Places SDK for Android. Idea is, going forward we’ll need to use this new version. I thought why not write a new post using this new version of the library. So, here in this post we’ll learn how to use Android Google Places Autocomplete feature using new Places SDK for Android. In today’s time in almost all the location based mobile application, we get feature to search location manually ourselves for various needs. The new Google Places SDK for Android provides places autocomplete service. It returns predictions of places in response to the search queries entered by the user in the search box. User can keep typing what they want to search, and the autocomplete service keeps returning list of suggestions based on the user input.

There are two ways of adding Google places autocomplete in android application:

In this tutorial, we will cover the first one i.e. by embedding
AutocompleteSupportFragment

App Demo

google-places-auto-complete-new-sdk
google-places-auto-complete-new-sdk

Tech Stack

Android Studio 3.3.2


JAVA for Android programming

Technology stack used in this blog

Create API Key

To get a working API key, you need to complete 3 activities. Get started by clicking in this link -. A new page will open up

  • Pick products (In this case, we’ll click on Places); click on Continue button.
  • Select a project. Here, you’ll see a drop-down list with the projects in your account. Select your project. However, In my case, I’ll select a project that I created previously with the name – ItcGoogleFeaturesDemo. You can create a new project as well if you want so. Click on Next button.
  • Last step is to setup a billing account ( if you don’t already have). Click on Enable billing option and a new page will open up. Setup our billing account here and this wizard will take you to creation of new API key. Note it down.
  • Alternatively, you can also head to this page and follow the official instruction on how to create a new API key

Create an empty project

  • Launch Android Studio and click: File –> New –> New Project…
  • A “Create New Project” dialog box will open; we’ll provide the app name and company domain. I have entered following details, you can provide the name/domain as per your choice and preference.
    • Name:- ItcGooglePlaceAutoCompleteNewPlacesSDK
    • Package Name:- placeautocomplete.iteritory.com
  • I have chosen API 16: Android 4.1 (Jelly Bean) as Minimum API level. Click Finishbutton.
  • I’ll change the app name a bit here, traverse and open res–> values –> strings.xml. Find the line with app_name attribute. Change the value to ““My Google Place App”.

Add dependency

Until now, the Places SDK for Android was made available through Google Play Services. But, the new version of the Places SDK for Android is distributed as a static client library.

  • In app-level build.gradle file, add a dependency for the new SDK client library, as below and then sync the gradle (At the time of writing this blog, following is the latest version. It’s possible that it gets newer version when you are reading. Upgrade the version as such).
    We’ll also add another dependency for a better UI and wrapping the google places autocomplete widget.

implementation ‘com.google.android.libraries.places:places:1.0.0’

implementation ‘com.android.support:cardview-v7:28.0.0’

After adding all the details, the app level build.gradle looks like below –

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "placeautocomplete.iteritory.com"
        minSdkVersion 16
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation 'com.google.android.libraries.places:places:1.0.0'
    implementation 'com.android.support:cardview-v7:28.0.0'
}

Add AutocompleteSupportFragment to layout file

Open the layout file (app -> res -> layout -> activity_main.xml). Add the
AutocompleteSupportFragment in the layout file. Also add a textbox to display the user selection. By default, this fragment has no border or background. We will wrap this fragment in a cardview to give a better look. After adding the necessary objects, the layout file looks like –

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <android.support.v7.widget.CardView
        android:id="@+id/idCardView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_marginTop="5dp"
        app:cardCornerRadius="4dp">
        <fragment android:id="@+id/autocomplete_fragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
            />
    </android.support.v7.widget.CardView>

    <TextView
        android:id="@+id/txtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Add necessary codes to handle the search result

Now that we have added the widget, it’ll show a cardview wrapping the autocomplete widget and also a textbox. So, at this point, if user types, the widget will show related suggestion based on user input. Next, we’ll also add few lines of codes to display what user have actually selected from the suggestion list. To do this, we will add few lines of codes in MainActivity.java. After adding the code, the MainActivity.java looks like below.

NOTE:- You have to replace the YOUR_API_KEY with your own key that you have obtained in the beginning of your tutorial. Also, I have mentioned the key directly in the code and I have done it only demonstration purpose. If you want to implement real-time project, you must secure the key and never mention the API key directly in the code

package placeautocomplete.iteritory.com;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

import java.util.Arrays;

import com.google.android.gms.common.api.Status;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.AutocompleteSupportFragment;
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener;
import com.google.android.libraries.places.api.Places;
//Add an import statement for the client library.


public class MainActivity extends AppCompatActivity {
    String TAG = "placeautocomplete";
    TextView txtView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txtView = findViewById(R.id.txtView);

        // Initialize Places.
        Places.initialize(getApplicationContext(), "YOUR_API_KEY");
        // Create a new Places client instance.
        PlacesClient placesClient = Places.createClient(this);

        // Initialize the AutocompleteSupportFragment.
        AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
                getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);

        // Specify the types of place data to return.
        autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME));

        // Set up a PlaceSelectionListener to handle the response.
        autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
            @Override
            public void onPlaceSelected(Place place) {
                // TODO: Get info about the selected place.
                txtView.setText(place.getName()+","+place.getId());
                Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
            }

            @Override
            public void onError(Status status) {
                // TODO: Handle the error.
                Log.i(TAG, "An error occurred: " + status);
            }
        });
    }
}

Conclusion

It was that easy to incorporate Google’s places auto complete feature in your app with just a few line’s of codes. Well, that’s it for today.

Filed under:
Previous article
Next article

34 responses

  1. Trương Huỳnh Hòa Avatar
    Trương Huỳnh Hòa

    Thanks for your tutorial, and i have a problem with it. When i find right location, it always shows “not found place” and sometime it will show location that i want but a little bit. May i get a explanation from you. Thanks!

  2. Konstantinos Nikoloutsos Avatar
    Konstantinos Nikoloutsos

    Thank you a lot for this one! It works like charm.
    (Is there any way to get rid of this initial searching bar and replace it with a simple textview which when clicked should open the dialog for finding a place.)
    You saved me a lot of development time.
    Kudos to you sir!

  3. Syeda Sheeba Avatar
    Syeda Sheeba

    Thank you soooo much sadruddin, you’re a saviour, it worked perfectly fine…. had been through all youtube videos but none of them had the latest service, thanks a lot…. ! <3

    1. Sadruddin Md Avatar

      Thank you 🙂

  4. Ameer Hamza Avatar
    Ameer Hamza

    Thanks Man. It Works 🙂

  5. Muhammad Luqman Avatar
    Muhammad Luqman

    Dear I have try your both codes but I don’t know why its not working can you help me

    1. Sadruddin Md Avatar

      Did you setup the API key in Google as mentioned in the tutorial?

  6. Muhammad Luqman Avatar
    Muhammad Luqman

    Yes I have mention Google API key but it not show suggestion all time I want to show places in Pakistan so how I can do this Search will only places in Pakistan

  7. prince Avatar
    prince

    Please can you do the autocomplete without the watermark powered by google, Thank you

  8. Prince Avatar
    Prince

    Thank you so much Sir for your time to make this tutorial,
    please can you make the one that will not come with the Powered by google Watermark, Thank you.

    1. Sadruddin Md Avatar

      Hi,
      You can’t. Please read this –>

  9. Farooq Ajaz Avatar
    Farooq Ajaz

    Sir I have try your both examples but I don’t know why its not working for me. its always show me “can’t load search result.” try again inside dialog….
    please help me…

  10. Jake Lowie Liwag Avatar
    Jake Lowie Liwag

    Hi , i followede everything that you have teach but my only problem is i cant set up my billing because i dont have a master card account 🙁

    1. Sadruddin Md Avatar

      Hi, pls check what other payment methods are available in your country. There may some other methods available apart from MasterCard

  11. rohith Avatar
    rohith

    Thank you so much Sadruddin Md, it helped me a lot searching for this from 2days

  12. Max Avatar
    Max

    Thank you for good explanation. I would like to aks “How can I change language?”. When I am searching country or city, it shows by default english suggestions. How we can change it? for example: language=ru or language=eng something like these.

    1. Sadruddin Md Avatar

      Hi max, apologies, replying very late 🙁
      Please take a look here.https://developers.google.com/places/web-service/autocomplete
      There is a section of language in this article. I hope it helps

  13. Diego Avatar
    Diego

    Hi,
    Thanks for your tutorial, it was very useful. I just have a problem. Do you know how to change the autocomplete widget to FULLSCREEN mode instead of OVERLAY mode?

  14. Jibu Avatar
    Jibu

    Thanks Sadruddin. My sincere gratitude.

    1. Sadruddin Md Avatar

      Thank you. Appreciate it 🙂

  15. Brown Avatar
    Brown

    Does it will work without a billing section? Just a doubt!!

    1. Sadruddin Md Avatar

      You mean whether you need to enable billing? Yes, you need to.

  16. Shayan Malinda Avatar
    Shayan Malinda

    Is there a way to use an EditText insetead of a fragment? Or can I style the fragment?

    1. Sadruddin Md Avatar

      Hi, you can create a custom search ui instead of using the one provided by autocomplete widget. Please check the android documentation for that

  17. alee Avatar
    alee

    method ‘void com.google.android.libraries.places.widget.AutocompleteSupportFragment.setPlaceFields(java.util.List)’ on a null object reference

    I’m face this

  18. arobit Avatar

    Error while autocompleting: OVER_QUERY_LIMIT

    this error is coming alway

  19. Ndivho Avatar
    Ndivho

    It is possible to convert the address from the search to a string?

  20. clinton jb Avatar
    clinton jb

    hi

    Is there any way to show only airport address in suggestion

  21. Sitansu Avatar
    Sitansu

    Place.Field.ID, Place.Field.NAME sir i’m getting error in FIELD can you please make me sure that what is FIELD how can i solve my problem please?

    1. Sadruddin Md Avatar

      I couldn’t really understand your question. What error are you getting?

  22. haris Avatar
    haris

    how to get post code can you please help ?

  23. abhirup patra Avatar
    abhirup patra

    Hi, can you tell how can i remove the text from the autocomplete fragment after the search is done?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.