Android AutoCompleteTextView With Google Place API

By | March 9, 2015

In the previous series we have seen tutorial on android simple autocompeletion and custom autocompeletion . In this article,  we will develop an Android application which populates an AutoCompleteTextView with Google Places Autocomplete api. The Place Autocomplete service is a web service from google that returns place predictions in response to an HTTP request , The service can be used to provide autocomplete functionality for text-based searches, by returning places addresses as a user types.

Generating Place API Key

The Google Place api key is available in Google Console Visit the link below and follow the steps to generate key . 

 https://code.google.com/apis/console

First we need to build a project with volley library which i have discussed in my previous tutorial how to Build project with Volley .

XML Layout

Create activity_main.xml file inside layout directory and add AutoCompeletionTextView to it

file : Main_Activity.xml

<LinearLayout
    xmlns:android=”http://schemas.android.com/apk/res/android”
    xmlns:tools=”http://schemas.android.com/tools”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:padding=”20dp”
    tools:context=”com.pavan.googleautocompletion.MainActivity” >

    <AutoCompleteTextView
        android:id=”@+id/autoCompleteTextView1″
        android:layout_width=”fill_parent”
        android:layout_height=”wrap_content”
        android:ems=”10″
        android:text=”” />

</LinearLayout>

Application Object

Create a class MyApplication which extends Application ,this application object represents singleton pattern , the purpose of this class is make volley request available  through out of the application

  1. The getInstance method of application class returns application object.
  2. The getReqQueue method returns the RequestQueue object.
  3. Inside addToReqQueue method we are adding calling add() method upon RequestObject and passing request as paramter to it .
  4. The cancelPendingReq is used for cancelling the request.

file : MyApplication.java

package com.pavan.googleautocompletion;

import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class MyApplication extends Application {

    private RequestQueue mRequestQueue;
    private static MyApplication mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized MyApplication getInstance() {
        return mInstance;
    }

    public RequestQueue getReqQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToReqQueue(Request<T> req, String tag) {

        getReqQueue().add(req);
    }

    public <T> void addToReqQueue(Request<T> req) {

        getReqQueue().add(req);
    }

    public void cancelPendingReq(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

Main Activity

  1. Create a class MainActivity and extend this class to Activity class and set the content of this activity with above defined XML Layout (activity_main.xml) .
  2. Set addTextChangeListener to the autocompeletionTextView when the user enter text make a request and update the suggestion list .

file : MainActivity.java

package com.pavan.googleautocompletion;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;

public class MainActivity extends Activity {
    String url;
    private static final String TAG_RESULT = “predictions”;
    JSONObject json;

    AutoCompleteTextView auto_tv;
    ArrayList<String> names;
    ArrayAdapter<String> adapter;
    String browserKey = “Your API KEY”;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        auto_tv = (AutoCompleteTextView) findViewById(R.id.searchAutoComplete);
        auto_tv.setThreshold(0);

        names = new ArrayList<String>();

        auto_tv.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {

            }

            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {

                if (s.toString().length() <= 3) {
                     names = new ArrayList<String>();
                    updateList(s.toString());
                }

            }
        });

    }

    public void updateList(String place) {
        String input = “”;

        try {
            input = “input=” + URLEncoder.encode(place, “utf-8”);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        String output = “json”;
        String parameter = input + “&types=geocode&sensor=true&key=”
                + browserKey;

        url = “https://maps.googleapis.com/maps/api/place/autocomplete/”
                + output + “?” + parameter;

        JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url,
                null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {

                        try {

                            JSONArray ja = response.getJSONArray(TAG_RESULT);

                            for (int i = 0; i < ja.length(); i++) {
                                JSONObject c = ja.getJSONObject(i);
                                String description = c.getString(“description”);
                                Log.d(“description”, description);
                                names.add(description);
                            }

                            adapter = new ArrayAdapter<String>(
                                    getApplicationContext(),
                                    android.R.layout.simple_list_item_1, names) {
                                @Override
                                public View getView(int position,
                                        View convertView, ViewGroup parent) {
                                    View view = super.getView(position,
                                            convertView, parent);
                                    TextView text = (TextView) view
                                            .findViewById(android.R.id.text1);
                                    text.setTextColor(Color.BLACK);
                                    return view;
                                }
                            };
                            auto_tv.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                        } catch (Exception e) {
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
        MyApplication.getInstance().addToReqQueue(jsonObjReq, “jreq”);
    }

}

Add Internet Permission Inside Manifest file

<uses-permission android:name=”android.permission.CHANGE_NETWORK_STATE” />
<uses-permission android:name=”android.permission.INTERNET” />

  • thank it is nice and efficient working tutorials. with less code and easy concept