<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>AutoCompleteTextView Archives - Truiton</title>
	<atom:link href="https://www.truiton.com/tag/autocompletetextview/feed/" rel="self" type="application/rss+xml" />
	<link></link>
	<description>Technology Reaching Us In Time - Online</description>
	<lastBuildDate>Sun, 01 Sep 2019 14:48:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://i0.wp.com/www.truiton.com/wp-content/uploads/2022/11/cropped-truiton_new_logo_half_white.png?fit=32%2C32&#038;ssl=1</url>
	<title>AutoCompleteTextView Archives - Truiton</title>
	<link></link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">54534495</site>	<item>
		<title>Android AutoCompleteTextView: Suggestions from Web Service Call</title>
		<link>https://www.truiton.com/2018/06/android-autocompletetextview-suggestions-from-webservice-call/</link>
					<comments>https://www.truiton.com/2018/06/android-autocompletetextview-suggestions-from-webservice-call/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Tue, 19 Jun 2018 08:37:26 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[AutoCompleteTextView]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=1857</guid>

					<description><![CDATA[<p>When building a mobile app, one of the most basic things to have in an app is an auto suggest box. It is such a common widget that anyone who&#8217;s using an app expects it to be there. But recently I realized that not many Android autocomplete examples exist on the internet where a web&#8230;&#160;<a href="https://www.truiton.com/2018/06/android-autocompletetextview-suggestions-from-webservice-call/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android AutoCompleteTextView: Suggestions from Web Service Call</span></a></p>
<p>The post <a href="https://www.truiton.com/2018/06/android-autocompletetextview-suggestions-from-webservice-call/">Android AutoCompleteTextView: Suggestions from Web Service Call</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" fetchpriority="high" decoding="async" width="950" height="530" data-attachment-id="1988" data-permalink="https://www.truiton.com/2018/06/android-autocompletetextview-suggestions-from-webservice-call/autocompletetextview-featured/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/03/AutoCompleteTextView-Featured.jpg?fit=950%2C530&amp;ssl=1" data-orig-size="950,530" data-comments-opened="1" data-image-title="AutoCompleteTextView &amp;#8211; Featured" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/03/AutoCompleteTextView-Featured.jpg?fit=950%2C530&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/03/AutoCompleteTextView-Featured.jpg?resize=950%2C530" alt="Android AutoCompleteTextView - Featured" class="wp-image-1988" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/03/AutoCompleteTextView-Featured.jpg?w=950&amp;ssl=1 950w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/03/AutoCompleteTextView-Featured.jpg?resize=300%2C167&amp;ssl=1 300w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/03/AutoCompleteTextView-Featured.jpg?resize=768%2C428&amp;ssl=1 768w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/03/AutoCompleteTextView-Featured.jpg?resize=640%2C357&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/03/AutoCompleteTextView-Featured.jpg?resize=600%2C335&amp;ssl=1 600w" sizes="(max-width: 950px) 100vw, 950px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">When building a mobile app, one of the most basic things to have in an app is an auto suggest box. It is such a common widget that anyone who&#8217;s using an app expects it to be there. But recently I realized that not many Android autocomplete examples exist on the internet where a web service or an API call is used to fetch data dynamically. Instead many tutorials are present showing the wrong practices of implementing an Android AutoCompleteTextView with web API call. Hence here I would show how I built an autosuggest feature on my Android app.</p>



<p class="wp-block-paragraph">To start with lets, understand the new additions in the <a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView" target="_blank" rel="noopener noreferrer">AutoCompleteTextView</a> widget. Recently with the release of Android support appcompat library 25.1.0 a background tint support was added and post which the new widget class was named as <a href="https://developer.android.com/reference/android/support/v7/widget/AppCompatAutoCompleteTextView" target="_blank" rel="noopener noreferrer"><code>AppCompatAutoCompleteTextView</code></a>. This new widget class is not much different from the original one, but since its an enhanced version of AutoCompleteTextView we will using this class for this Android AutoCompleteTextView with and API call tutorial.</p>



<h2 class="wp-block-heading">Android AutoCompleteTextView with data from Web API Call example</h2>



<p class="wp-block-paragraph">To start with, lets define the objectives of this tutorial. Here we will create and Android AutoCompleteTextView example, where data is fetched dynamically from a web API call. Once the data is fetched dynamically based on the user&#8217;s input, we would display it accordingly in a drop down scrolling list. The Android&nbsp;AutoCompleteTextView implementation is so flexible that even its dropdown can also be customised. But to keep things simple and focused, we would keep this out of the scope of this example.</p>



<h3 class="wp-block-heading">1. Prerequisites</h3>



<p class="wp-block-paragraph">To make any API call in an android app, we must have a REST framework implemented. So that we can have some basic set of features relating to web API call. Since <a href="http://www.truiton.com/2015/02/android-volley-example/" target="_blank" rel="noopener noreferrer">Android Volley</a> is a very simple framework, we would be using volley in this example to make API calls. But just in case, if you are comfortable with any other REST framework, please feel free to use that in your app.</p>



<p class="wp-block-paragraph">First lets add internet permission in the manifest:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;manifest ...>

    &lt;uses-permission android:name="android.permission.INTERNET" />

    &lt;application .... >
    &lt;/application>
&lt;/manifest></pre>



<p class="wp-block-paragraph">Secondly lets define a basic class to make an API call through the app.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.autosuggesttextviewapicall;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

/**
 * Created by MG on 04-03-2018.
 */

public class ApiCall {
    private static ApiCall mInstance;
    private RequestQueue mRequestQueue;
    private static Context mCtx;

    public ApiCall(Context ctx) {
        mCtx = ctx;
        mRequestQueue = getRequestQueue();
    }

    public static synchronized ApiCall getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new ApiCall(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public &lt;T> void addToRequestQueue(Request&lt;T> req) {
        getRequestQueue().add(req);
    }

    public static void make(Context ctx, String query, Response.Listener&lt;String>
            listener, Response.ErrorListener errorListener) {
        String url = "https://itunes.apple.com/search?term=" + query
                + "&amp;country=US";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                listener, errorListener);
        ApiCall.getInstance(ctx).addToRequestQueue(stringRequest);
    }
}
</pre>



<p class="wp-block-paragraph">Method to take note of in the class above is <code>make</code>, as this is the only static method in this class. This method would be used to make an API call for the Android&nbsp;AutoCompleteTextView implementation ahead. Internally this method would create a request queue for volley and handle all the network I/O itself. Also in the above class, I just defined a basic example of Android volley request queue, through which we will be making an API call for the implementation of Android&nbsp;AutoCompleteTextView showing dynamic data from the same. To learn more in detail on Android volley please refer to my <a href="http://www.truiton.com/2015/02/android-volley-example/" target="_blank" rel="noopener noreferrer">tutorial on it here</a>.</p>



<h3 class="wp-block-heading">2. Define an Adapter for Android&nbsp;AutoCompleteTextView with dynamic data from API call</h3>



<p class="wp-block-paragraph">As you may know, the drop down list shown on top of an&nbsp;<code>AutoCompleteTextView</code> is just a <code>ListView</code> inside of the overflow. Therefore as per principle, we have to make an adapter for the underlying <code>ListView</code>. Now since we are going to use an adapter, where only data needs to be shown in a form of list and also we don&#8217;t need any sort of processing on the list therefore we would use an <a href="https://developer.android.com/reference/android/widget/ArrayAdapter" target="_blank" rel="noopener noreferrer"><code>ArrayAdapter</code></a>. But keeping the future improvements in mind we will also implement a <code>Filterable</code> interface. This can help us in processing the list as well without making an API call.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.autosuggesttextviewapicall;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;

import java.util.ArrayList;
import java.util.List;

public class AutoSuggestAdapter extends ArrayAdapter&lt;String> implements Filterable {
    private List&lt;String> mlistData;

    public AutoSuggestAdapter(@NonNull Context context, int resource) {
        super(context, resource);
        mlistData = new ArrayList&lt;>();
    }

    public void setData(List&lt;String> list) {
        mlistData.clear();
        mlistData.addAll(list);
    }

    @Override
    public int getCount() {
        return mlistData.size();
    }

    @Nullable
    @Override
    public String getItem(int position) {
        return mlistData.get(position);
    }

    /**
     * Used to Return the full object directly from adapter.
     *
     * @param position
     * @return
     */
    public String getObject(int position) {
        return mlistData.get(position);
    }

    @NonNull
    @Override
    public Filter getFilter() {
        Filter dataFilter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    filterResults.values = mlistData;
                    filterResults.count = mlistData.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null &amp;&amp; (results.count > 0)) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
        return dataFilter;
    }
}
</pre>



<p class="wp-block-paragraph">The above piece of code would turn out to be a fully functional <code>ArrayAdapter</code>, with the capability of setting the data without instantiating the adapter object once again. Also this would have a <code>Filterable</code> implementation, therefore it would be perfect example for an Android&nbsp;<code>AutoCompleteTextView</code>&nbsp;where suggestions from an API call are shown.</p>



<h3 class="wp-block-heading">3. Using Android&nbsp;AppCompatAutoCompleteTextView with web API call</h3>



<p class="wp-block-paragraph">As mentioned earlier for this tutorial we will be using Android&nbsp;AppCompatAutoCompleteTextView widget for building an auto suggest experience, as this widget gives an extra advantage over standard implementation. That is with this new one, we can set background tint color and modify it dynamically with <code>ViewCompat</code> methods. Lets start by defining a layout:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;?xml version="1.0" encoding="utf-8"?>
&lt;RelativeLayout
    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"
    tools:context="com.truiton.autosuggesttextviewapicall.MainActivity">

    &lt;android.support.v7.widget.AppCompatAutoCompleteTextView
        android:id="@+id/auto_complete_edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_margin="10dp"
        android:inputType="text"
        android:maxLines="1"/>

    &lt;TextView
        android:id="@+id/selected_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/auto_complete_edit_text"
        android:layout_marginTop="50dp"
        android:padding="20dp"/>

&lt;/RelativeLayout>
</pre>



<p class="wp-block-paragraph">Next to implement an Android AppCompatAutoCompleteTextView where&nbsp;suggestions come from a WebService call, we need to define an activity where all of this is done.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.autosuggesttextviewapicall;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final int TRIGGER_AUTO_COMPLETE = 100;
    private static final long AUTO_COMPLETE_DELAY = 300;
    private Handler handler;
    private AutoSuggestAdapter autoSuggestAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final AppCompatAutoCompleteTextView autoCompleteTextView =
                findViewById(R.id.auto_complete_edit_text);
        final TextView selectedText = findViewById(R.id.selected_item);

        //Setting up the adapter for AutoSuggest
        autoSuggestAdapter = new AutoSuggestAdapter(this,
                android.R.layout.simple_dropdown_item_1line);
        autoCompleteTextView.setThreshold(2);
        autoCompleteTextView.setAdapter(autoSuggestAdapter);
        autoCompleteTextView.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView&lt;?> parent, View view,
                                            int position, long id) {
                        selectedText.setText(autoSuggestAdapter.getObject(position));
                    }
                });

        autoCompleteTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int
                    count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                handler.removeMessages(TRIGGER_AUTO_COMPLETE);
                handler.sendEmptyMessageDelayed(TRIGGER_AUTO_COMPLETE,
                        AUTO_COMPLETE_DELAY);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == TRIGGER_AUTO_COMPLETE) {
                    if (!TextUtils.isEmpty(autoCompleteTextView.getText())) {
                        makeApiCall(autoCompleteTextView.getText().toString());
                    }
                }
                return false;
            }
        });
    }

    private void makeApiCall(String text) {
        ApiCall.make(this, text, new Response.Listener&lt;String>() {
            @Override
            public void onResponse(String response) {
                //parsing logic, please change it as per your requirement
                List&lt;String> stringList = new ArrayList&lt;>();
                try {
                    JSONObject responseObject = new JSONObject(response);
                    JSONArray array = responseObject.getJSONArray("results");
                    for (int i = 0; i &lt; array.length(); i++) {
                        JSONObject row = array.getJSONObject(i);
                        stringList.add(row.getString("trackName"));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //IMPORTANT: set data here and notify
                autoSuggestAdapter.setData(stringList);
                autoSuggestAdapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }
}
</pre>



<p class="wp-block-paragraph">The above implementation of an Android&nbsp;<code>AppCompatAutoCompleteTextView</code> is a bit different from the regular implementation. Here firstly an adapter is instantiated, which we defined in the previous section of tutorial. Secondly an instance of&nbsp;<code>AdapterView.OnItemClickListener()</code> is set, to capture the clicks on the dropdown items. Next one of the most important part, a <code>TextWatcher</code> is attached to the <code>AutoCompleteTextView</code>. This <code>TextWatcher</code> captures all the all the user inputs and sends it to a handler. Here in this Android&nbsp;AutoCompleteTextView example, we are processing the changes of <code>EditText</code> via a delayed handler. In a way, this approach saves us some unnecessary web API calls, as a delay in consecutive requests is introduced with the help of <code>Handler</code> class. Once a successful call is reached to the handler, we make an API call which returns the results in expected form and they are shown with the help of an Adapter. This way, data is shown on the AutoCompleteTextView drop down. To view the full source code, please checkout the link below:</p>



<p class="wp-block-paragraph" style="text-align:center"><a class="fasc-button fasc-size-large fasc-type-flat fasc-rounded-medium ico-fa fasc-ico-before fa-github" style="background-color: #0364af; color: #ffffff;" target="_blank" rel="noopener noreferrer" href="https://github.com/Truiton/AutoSuggestTextViewAPICall">Full Source Code</a></p>



<p class="wp-block-paragraph">This is how the output of the above example would look:</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" decoding="async" width="665" height="1266" data-attachment-id="1989" data-permalink="https://www.truiton.com/2018/06/android-autocompletetextview-suggestions-from-webservice-call/android-autocompletetextview/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/06/Android-AutoCompleteTextView.png?fit=665%2C1266&amp;ssl=1" data-orig-size="665,1266" data-comments-opened="1" data-image-title="Android AutoCompleteTextView" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/06/Android-AutoCompleteTextView.png?fit=538%2C1024&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/06/Android-AutoCompleteTextView.png?resize=665%2C1266" alt="Android AutoCompleteTextView" class="wp-image-1989" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/06/Android-AutoCompleteTextView.png?w=665&amp;ssl=1 665w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/06/Android-AutoCompleteTextView.png?resize=158%2C300&amp;ssl=1 158w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/06/Android-AutoCompleteTextView.png?resize=538%2C1024&amp;ssl=1 538w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/06/Android-AutoCompleteTextView.png?resize=640%2C1218&amp;ssl=1 640w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2018/06/Android-AutoCompleteTextView.png?resize=600%2C1142&amp;ssl=1 600w" sizes="(max-width: 665px) 100vw, 665px" /></figure></div>



<h2 class="wp-block-heading">Some Important properties of Android AutoCompleteTextView</h2>



<p class="wp-block-paragraph">Now that we have a fair understanding of how an <a href="http://www.truiton.com/2018/06/android-autocompletetextview-suggestions-from-webservice-call/">Android&nbsp;AutoCompleteTextView</a> works, lets have a look at some of its frequently used properties:</p>



<ul class="wp-block-list"><li><a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#setThreshold(int)">setThreshold(int threshold)</a> &#8211; This sets a character input threshold, for triggering the dropdown.</li><li><a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#setCompletionHint(java.lang.CharSequence)">setCompletionHint(CharSequence&nbsp;hint)</a> &#8211; Once the threshold is reached and a dropdown is shown, over the bottom this completion hint is also shown.</li><li><a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#setDropDownBackgroundResource(int)">setDropDownBackgroundResource(int id)</a> &#8211; With the help of this method, you can set a background resource for the dropdown list.</li><li><a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#setDropDownBackgroundDrawable(android.graphics.drawable.Drawable)">setDropDownBackgroundDrawable(Drawable&nbsp;d)</a> &#8211; With this method, we can set a background drawable for auto suggest list. But on a separate note, if you wish to style the Android AutoCompleteTextView dropdown background you can also consider styling the list item of dropdown by using a custom xml for inflating the item(explained in next section).</li></ul>



<h2 class="wp-block-heading">Android AutoCompleteTextView dropdown positioning</h2>



<p class="wp-block-paragraph">At times when making an Android autosuggest, we wish to move the dropdown and attach it to some other view on screen. This may sound complex, but its very simple to implement with Android&nbsp;AutoCompleteTextView, we just need to define a few properties in xml. To get started, lets discuss some properties for dropdown positioning of Andorid AutoCompleteTextView:</p>



<ul class="wp-block-list"><li><a rel="noopener noreferrer" href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#attr_android:dropDownAnchor" target="_blank">android:dropDownAnchor=&#8221;@id/selected_item&#8221;</a> &#8211; This property basically defines the view to which the dropdown popup of Android AutoSuggest should be attached to. This property can also be used by a java method <a rel="noopener noreferrer" href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#setDropDownAnchor(int)" target="_blank">setDropDownAnchor()</a>.</li></ul>



<p class="wp-block-paragraph">When using the above property, if the dropdown length goes beyond the keyboard height, in some scenarios it will be automatically detached and positioned on top of the screen. To avoid this behaviour of Android AutoCompleteTextView, we can use the following properties, these will help in curbing the mentioned behaviour:</p>



<ul class="wp-block-list"><li><a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#attr_android:dropDownHeight">android:dropDownHeight</a> &#8211; sets the height of auto suggest drop down.</li><li><a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#attr_android:dropDownHorizontalOffset">android:dropDownHorizontalOffset</a> &#8211; sets the horizontal offset of the list from attached view.</li><li><a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#attr_android:dropDownVerticalOffset">android:dropDownVerticalOffset</a> &#8211; sets the vertical offset of the list from attached view.</li><li><a href="https://developer.android.com/reference/android/widget/AutoCompleteTextView.html#attr_android:dropDownWidth">android:dropDownWidth</a> &#8211; sets the dropdown list width.</li></ul>



<p class="wp-block-paragraph">Now addressing the issue of custom views in Android&nbsp;AutoCompleteTextView, to do so in the above piece of code firstly you need to make a new layout for the custom list item. Next, that xml resource needs to be specified in the adapter initiation like this: <code>new AutoSuggestAdapter(this,R.layout.custom_dropdown_item);</code>. Once this is done, in the adapter you need to implement the&nbsp;<code>getView()</code> method and use the custom layout xml. This way as a result you would see a list dropdown in an Android&nbsp;AutoCompleteTextView with a custom layout. That said, lets conclude this tutorial and please connect with us on Twitter, Facebook and Google+ for more updates.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2018/06/android-autocompletetextview-suggestions-from-webservice-call/">Android AutoCompleteTextView: Suggestions from Web Service Call</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2018/06/android-autocompletetextview-suggestions-from-webservice-call/feed/</wfw:commentRss>
			<slash:comments>5</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1857</post-id>	</item>
		<item>
		<title>Android Places API: Autocomplete with getPlaceByID</title>
		<link>https://www.truiton.com/2015/04/android-places-api-autocomplete-getplacebyid/</link>
					<comments>https://www.truiton.com/2015/04/android-places-api-autocomplete-getplacebyid/#comments</comments>
		
		<dc:creator><![CDATA[Mohit Gupt]]></dc:creator>
		<pubDate>Fri, 17 Apr 2015 14:21:43 +0000</pubDate>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Android Places API]]></category>
		<category><![CDATA[AutoCompleteTextView]]></category>
		<guid isPermaLink="false">http://www.truiton.com/?p=1153</guid>

					<description><![CDATA[<p>A new API was released for Android, by the name of Google Places API. This API offers easy to use methods, through which Google Places data can be accessed on Android. The main advantage of this API is, while developing apps, you may not need to parse data from a web service. As all the&#8230;&#160;<a href="https://www.truiton.com/2015/04/android-places-api-autocomplete-getplacebyid/" rel="bookmark">Read More &#187;<span class="screen-reader-text">Android Places API: Autocomplete with getPlaceByID</span></a></p>
<p>The post <a href="https://www.truiton.com/2015/04/android-places-api-autocomplete-getplacebyid/">Android Places API: Autocomplete with getPlaceByID</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="950" height="534" data-attachment-id="1154" data-permalink="https://www.truiton.com/2015/04/android-places-api-autocomplete-getplacebyid/android-places-api-autocomplete/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.jpg?fit=950%2C534&amp;ssl=1" data-orig-size="950,534" data-comments-opened="1" data-image-title="Android Places API Autocomplete" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.jpg?fit=950%2C534&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.jpg?resize=950%2C534" alt="Android Places API Autocomplete" class="wp-image-1154" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.jpg?w=950&amp;ssl=1 950w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.jpg?resize=600%2C337&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.jpg?resize=300%2C169&amp;ssl=1 300w" sizes="auto, (max-width: 950px) 100vw, 950px" /></figure></div>



<p class="wp-block-paragraph"></p>



<p class="wp-block-paragraph">A new API was released for Android, by the name of <a title="Google Places API for Android" href="https://developers.google.com/places/android/" target="_blank" rel="noopener noreferrer">Google Places API</a>. This API offers easy to use methods, through which Google Places data can be accessed on Android. The main advantage of this API is, while developing apps, you may not need to parse data from a web service. As all the data is exchanged through <a title="GoogleApiClient" href="https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.html" target="_blank" rel="noopener noreferrer">GoogleApiClient</a> automatically. Google places API for android gives full access to Google&#8217;s database for places. Although this API is not completely free, and is offered under <a title="Google Places API for Android Quota" href="https://developers.google.com/places/android/usage" target="_blank" rel="noopener noreferrer">quota based plans</a>, but still its a good trade off when compared to the earlier approach. Android Places API has many new methods for accessing Google places database, but here we will be discussing Autocomplete feature of it, to get a place Id. Further we will be using this unique Place ID to get place details by ID.</p>



<p class="wp-block-paragraph">Earlier when we had to detect places around our current location in Android, we had to make an API call to <a title="Google APIs for Maps" href="https://developers.google.com/places/webservice/intro" target="_blank" rel="noopener noreferrer">Google Maps APIs for Places</a>, with our current latitude and longitude. But now one of the greatest things about new Android Places API is that, to get places around your current place, you don&#8217;t need to pass LatLongs. As the new Android places API handles all of this, and much more by itself. If you wish to know in detail about more features of Google Places API for Android, please refer to this <a title="Using the New Google Places API for Android" href="http://www.truiton.com/2015/04/using-new-google-places-api-android/" target="_blank" rel="noopener noreferrer">Android Places API tutorial</a>, as here we are focused on getting a place Id using autocomplete feature of Android Places API.</p>



<p class="wp-block-paragraph">Before starting this Android Places API with autocomplete and getPlaceById example, first include Google Play services in your app, by adding this in the dependencies section:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">compile 'com.google.android.gms:play-services-places:10.2.1'</pre>



<p class="wp-block-paragraph">Add this in application tag of your manifest :</p>



<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version"/></pre>



<p class="wp-block-paragraph">Add these permissions in the manifest:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
&lt;uses-permission android:name="android.permission.INTERNET"/></pre>



<p class="wp-block-paragraph">For more details on using play services please refer to this <a title="Setting Up Google Play Services" href="https://developer.android.com/google/play-services/setup.html" target="_blank" rel="noopener noreferrer">setting up play services</a> page. Next have a look at the steps to generate Places API for Android key</p>



<ol class="wp-block-list"><li>Create a project in <a title="Google Developers Console" href="https://console.developers.google.com/" target="_blank" rel="noopener noreferrer">Google Developers console</a> or use an existing one.</li><li>Navigate to &#8220;APIs &amp; Auth&#8221; section, select APIs.</li><li>Search and select &#8220;Places API for Android&#8221;.</li><li>Enable it.</li><li>Then go to the credentials section.</li><li>Create a key for Android application.</li><li>Enter your SHA1 fingerprint with package name in the desired format. Use this <a title="Obtaining SHA1 Fingerprint from Android Keystore" href="http://www.truiton.com/2015/04/obtaining-sha1-fingerprint-android-keystore/" target="_blank" rel="noopener noreferrer">SHA1 fingerprint tutorial</a> to get your fingerprint.</li><li>Paste the API key in a meta tag under the application tag of your Android Manifest as shown below.</li></ol>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="{YOUR_API_KEY}"/></pre>



<h2 class="wp-block-heading">Android Places API &#8211; Autocomplete with Suggestions</h2>



<p class="wp-block-paragraph">As you might be aware, that Google&#8217;s Places API for Web has a very powerful autocomplete suggestions tool. But also it was not easy to integrate in an Android app. Now since Google has introduced Places API for Android with support for <a title="Android Places API Autocomplete" href="https://developers.google.com/places/android/autocomplete" target="_blank" rel="noopener noreferrer">Autocomplete suggestions</a>, things have gone a little easy. Place Autocomplete API has now been completely reinvented and supports many features like location boundaries, filtering place types and much more. Whats even better is that this API can be directly integrated into an Android AutoCompleteTextView, where Places API suggestions could be shown, like below.</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="600" height="900" data-attachment-id="1157" data-permalink="https://www.truiton.com/2015/04/android-places-api-autocomplete-getplacebyid/android-places-api-autocomplete-2/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.png?fit=600%2C900&amp;ssl=1" data-orig-size="600,900" data-comments-opened="1" data-image-title="Android Places API Autocomplete" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.png?fit=600%2C900&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.png?resize=600%2C900" alt="Android Places API Autocomplete" class="wp-image-1157" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.png?w=600&amp;ssl=1 600w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.png?resize=200%2C300&amp;ssl=1 200w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Autocomplete.png?resize=300%2C450&amp;ssl=1 300w" sizes="auto, (max-width: 600px) 100vw, 600px" /></figure></div>



<p class="wp-block-paragraph">Have a look at the layout:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="xml" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">&lt;RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
                android:paddingLeft="@dimen/activity_horizontal_margin"
                android:paddingRight="@dimen/activity_horizontal_margin"
                android:paddingTop="@dimen/activity_vertical_margin"
                tools:context=".MainActivity">

    &lt;AutoCompleteTextView
        android:id="@+id/autoCompleteTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:hint="Enter Place Here"/>

    &lt;TextView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/autoCompleteTextView"
        android:layout_marginTop="20dp"
        android:text="Selected Place:"
        android:textStyle="bold"/>

    &lt;TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/header"
        android:layout_marginTop="20dp"/>

    &lt;TextView
        android:id="@+id/address"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/name"/>

    &lt;TextView
        android:id="@+id/place_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/address"/>

    &lt;TextView
        android:id="@+id/phone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/place_id"
        android:autoLink="phone"/>

    &lt;TextView
        android:id="@+id/web"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/phone"
        android:autoLink="web"/>

    &lt;TextView
        android:id="@+id/att"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:autoLink="web"/>

    &lt;ImageView
        android:id="@+id/poweredBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/att"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:src="@drawable/powered_by_google_light"/>

    &lt;ImageView
        android:id="@+id/truiton_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_above="@+id/poweredBy"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="-20dp"
        android:src="@mipmap/truiton_short_no_back"/>

&lt;/RelativeLayout>
</pre>



<p class="wp-block-paragraph">Before making use of Android Places API for Autocomplete suggestions please remember to show the powered by Google attribution as per guidelines. Also please remember to show third party attributions (if any) as shown above.</p>



<p class="wp-block-paragraph">Now before getting place id and details from an AutoCompleteTextView, we need to customize an ArrayAdapter which would be attached to this AutoCompleteTextView. This adapter would internally make calls to the Google Places API for suggestions by using <a href="https://developer.android.com/reference/com/google/android/gms/location/places/GeoDataApi.html"><code>GeoDataApi.getAutocompletePredictions()</code></a> method. Have a look at the code:</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.placeapiautocomplete;

import android.content.Context;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.AutocompleteFilter;
import com.google.android.gms.location.places.AutocompletePrediction;
import com.google.android.gms.location.places.AutocompletePredictionBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLngBounds;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.TimeUnit;

public class PlaceArrayAdapter
        extends ArrayAdapter&lt;PlaceArrayAdapter.PlaceAutocomplete&gt; implements Filterable {
    private static final String TAG = "PlaceArrayAdapter";
    private GoogleApiClient mGoogleApiClient;
    private AutocompleteFilter mPlaceFilter;
    private LatLngBounds mBounds;
    private ArrayList&lt;PlaceAutocomplete&gt; mResultList;

    /**
     * Constructor
     *
     * @param context  Context
     * @param resource Layout resource
     * @param bounds   Used to specify the search bounds
     * @param filter   Used to specify place types
     */
    public PlaceArrayAdapter(Context context, int resource, LatLngBounds bounds,
                             AutocompleteFilter filter) {
        super(context, resource);
        mBounds = bounds;
        mPlaceFilter = filter;
    }

    public void setGoogleApiClient(GoogleApiClient googleApiClient) {
        if (googleApiClient == null || !googleApiClient.isConnected()) {
            mGoogleApiClient = null;
        } else {
            mGoogleApiClient = googleApiClient;
        }
    }

    @Override
    public int getCount() {
        return mResultList.size();
    }

    @Override
    public PlaceAutocomplete getItem(int position) {
        return mResultList.get(position);
    }

    private ArrayList&lt;PlaceAutocomplete&gt; getPredictions(CharSequence constraint) {
        if (mGoogleApiClient != null) {
            Log.i(TAG, "Executing autocomplete query for: " + constraint);
            PendingResult&lt;AutocompletePredictionBuffer&gt; results =
                    Places.GeoDataApi
                            .getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
                                    mBounds, mPlaceFilter);
            // Wait for predictions, set the timeout.
            AutocompletePredictionBuffer autocompletePredictions = results
                    .await(60, TimeUnit.SECONDS);
            final Status status = autocompletePredictions.getStatus();
            if (!status.isSuccess()) {
                Toast.makeText(getContext(), "Error: " + status.toString(),
                        Toast.LENGTH_SHORT).show();
                Log.e(TAG, "Error getting place predictions: " + status
                        .toString());
                autocompletePredictions.release();
                return null;
            }

            Log.i(TAG, "Query completed. Received " + autocompletePredictions.getCount()
                    + " predictions.");
            Iterator&lt;AutocompletePrediction&gt; iterator = autocompletePredictions.iterator();
            ArrayList resultList = new ArrayList&lt;&gt;(autocompletePredictions.getCount());
            while (iterator.hasNext()) {
                AutocompletePrediction prediction = iterator.next();
                resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),
                        prediction.getFullText(null)));
            }
            // Buffer release
            autocompletePredictions.release();
            return resultList;
        }
        Log.e(TAG, "Google API client is not connected.");
        return null;
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults results = new FilterResults();
                if (constraint != null) {
                    // Query the autocomplete API for the entered constraint
                    mResultList = getPredictions(constraint);
                    if (mResultList != null) {
                        // Results
                        results.values = mResultList;
                        results.count = mResultList.size();
                    }
                }
                return results;
            }

            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null &amp;&amp; results.count &gt; 0) {
                    // The API returned at least one result, update the data.
                    notifyDataSetChanged();
                } else {
                    // The API did not return any results, invalidate the data set.
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }

    class PlaceAutocomplete {

        public CharSequence placeId;
        public CharSequence description;

        PlaceAutocomplete(CharSequence placeId, CharSequence description) {
            this.placeId = placeId;
            this.description = description;
        }

        @Override
        public String toString() {
            return description.toString();
        }
    }
}
</pre>



<p class="wp-block-paragraph">The above code simply calls the <a href="https://developer.android.com/reference/com/google/android/gms/location/places/GeoDataApi.html" target="_blank" rel="noopener noreferrer"><code>GeoDataApi.getAutocompletePredictions()</code></a> method to get the Places API autocomplete suggestions, on change of every character. This API call also supports a timeout limit by using the <code>await(60, TimeUnit.SECONDS)</code> method, where the first argument is used to specify the limit. One of the main things to be noted in the ArrayAdapter above is that, an inner class&nbsp;<code>PlaceAutocomplete</code> is being used to store and return the description and IDs of the places to main activity where the Android Places API would be called once again for selected ID.</p>



<h2 class="wp-block-heading">Android Places API &#8211; Get Place by ID</h2>



<p class="wp-block-paragraph">Another API which is offered under the Google Places API for Android suite is <a title="Android Places API Details" href="https://developers.google.com/places/android/place-details" target="_blank" rel="noopener noreferrer">Place Details API</a>. This API is also called using the <a title="GoogleApiClient" href="https://developer.android.com/reference/com/google/android/gms/common/api/GoogleApiClient.html" target="_blank" rel="noopener noreferrer">GoogleApiClient</a>, but a place ID is required to make the call. Using <a href="https://developer.android.com/reference/com/google/android/gms/location/places/GeoDataApi.html" target="_blank" rel="noopener noreferrer"><code>GeoDataApi.getPlaceById</code></a> method we can get all the details of requested place. I would like to remind once again here that, calling this API is not completely free, please refer to this <a title="Usage Quota" href="https://developers.google.com/places/android/usage" target="_blank" rel="noopener noreferrer">usage limits</a> page. Now lets have a look at the main activity class where both these Autocomplete and Place Details by ID APIs are used in a complementing way.</p>



<pre class="EnlighterJSRAW" data-enlighter-language="java" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">package com.truiton.placeapiautocomplete;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;


public class MainActivity extends AppCompatActivity implements
        GoogleApiClient.OnConnectionFailedListener,
        GoogleApiClient.ConnectionCallbacks {
    private static final String LOG_TAG = "MainActivity";
    private static final int GOOGLE_API_CLIENT_ID = 0;
    private AutoCompleteTextView mAutocompleteTextView;
    private TextView mNameTextView;
    private TextView mAddressTextView;
    private TextView mIdTextView;
    private TextView mPhoneTextView;
    private TextView mWebTextView;
    private TextView mAttTextView;
    private GoogleApiClient mGoogleApiClient;
    private PlaceArrayAdapter mPlaceArrayAdapter;
    private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
            new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                .addApi(Places.GEO_DATA_API)
                .enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
                .addConnectionCallbacks(this)
                .build();
        mAutocompleteTextView = (AutoCompleteTextView) findViewById(R.id
                .autoCompleteTextView);
        mAutocompleteTextView.setThreshold(3);
        mNameTextView = (TextView) findViewById(R.id.name);
        mAddressTextView = (TextView) findViewById(R.id.address);
        mIdTextView = (TextView) findViewById(R.id.place_id);
        mPhoneTextView = (TextView) findViewById(R.id.phone);
        mWebTextView = (TextView) findViewById(R.id.web);
        mAttTextView = (TextView) findViewById(R.id.att);
        mAutocompleteTextView.setOnItemClickListener(mAutocompleteClickListener);
        mPlaceArrayAdapter = new PlaceArrayAdapter(this, android.R.layout.simple_list_item_1,
                BOUNDS_MOUNTAIN_VIEW, null);
        mAutocompleteTextView.setAdapter(mPlaceArrayAdapter);
    }

    private AdapterView.OnItemClickListener mAutocompleteClickListener
            = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
            final PlaceArrayAdapter.PlaceAutocomplete item = mPlaceArrayAdapter.getItem(position);
            final String placeId = String.valueOf(item.placeId);
            Log.i(LOG_TAG, "Selected: " + item.description);
            PendingResult&lt;PlaceBuffer&gt; placeResult = Places.GeoDataApi
                    .getPlaceById(mGoogleApiClient, placeId);
            placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
            Log.i(LOG_TAG, "Fetching details for ID: " + item.placeId);
        }
    };

    private ResultCallback&lt;PlaceBuffer&gt; mUpdatePlaceDetailsCallback
            = new ResultCallback&lt;PlaceBuffer&gt;() {
        @Override
        public void onResult(PlaceBuffer places) {
            if (!places.getStatus().isSuccess()) {
                Log.e(LOG_TAG, "Place query did not complete. Error: " +
                        places.getStatus().toString());
                return;
            }
            // Selecting the first object buffer.
            final Place place = places.get(0);
            CharSequence attributions = places.getAttributions();

            mNameTextView.setText(Html.fromHtml(place.getName() + ""));
            mAddressTextView.setText(Html.fromHtml(place.getAddress() + ""));
            mIdTextView.setText(Html.fromHtml(place.getId() + ""));
            mPhoneTextView.setText(Html.fromHtml(place.getPhoneNumber() + ""));
            mWebTextView.setText(place.getWebsiteUri() + "");
            if (attributions != null) {
                mAttTextView.setText(Html.fromHtml(attributions.toString()));
            }
        }
    };

    @Override
    public void onConnected(Bundle bundle) {
        mPlaceArrayAdapter.setGoogleApiClient(mGoogleApiClient);
        Log.i(LOG_TAG, "Google Places API connected.");

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.e(LOG_TAG, "Google Places API connection failed with error code: "
                + connectionResult.getErrorCode());

        Toast.makeText(this,
                "Google Places API connection failed with error code:" +
                        connectionResult.getErrorCode(),
                Toast.LENGTH_LONG).show();
    }

    @Override
    public void onConnectionSuspended(int i) {
        mPlaceArrayAdapter.setGoogleApiClient(null);
        Log.e(LOG_TAG, "Google Places API connection suspended.");
    }
}
</pre>



<p class="wp-block-paragraph">This would result in a screen like this:</p>



<div class="wp-block-image"><figure class="aligncenter"><img data-recalc-dims="1" loading="lazy" decoding="async" width="500" height="805" data-attachment-id="1160" data-permalink="https://www.truiton.com/2015/04/android-places-api-autocomplete-getplacebyid/android-places-api-get-place-id/" data-orig-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Get-Place-Id.png?fit=500%2C805&amp;ssl=1" data-orig-size="500,805" data-comments-opened="1" data-image-title="Android Places API Get Place Id" data-image-description="" data-image-caption="" data-large-file="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Get-Place-Id.png?fit=500%2C805&amp;ssl=1" src="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Get-Place-Id.png?resize=500%2C805" alt="Android Places API Get Place Id" class="wp-image-1160" srcset="https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Get-Place-Id.png?w=500&amp;ssl=1 500w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Get-Place-Id.png?resize=186%2C300&amp;ssl=1 186w, https://i0.wp.com/www.truiton.com/wp-content/uploads/2015/04/Android-Places-API-Get-Place-Id.png?resize=300%2C483&amp;ssl=1 300w" sizes="auto, (max-width: 500px) 100vw, 500px" /></figure></div>



<p class="wp-block-paragraph">Now lets understand, how to get place suggestions from the API, in an AutoCompleteTextView using the <a href="https://developer.android.com/reference/com/google/android/gms/location/places/GeoDataApi.html" target="_blank" rel="noopener noreferrer"><code>GeoDataApi.getAutocompletePredictions()</code></a> method and further displaying the detailed information using <a href="https://developer.android.com/reference/com/google/android/gms/location/places/GeoDataApi.html" target="_blank" rel="noopener noreferrer"><code>GeoDataApi.getPlaceById</code></a> method on screen. To get full understanding on how this works have a look at code sample repository below:</p>



<p class="wp-block-paragraph" style="text-align:center"><a class="fasc-button fasc-size-large fasc-type-flat fasc-rounded-medium ico-fa fasc-ico-before fa-github" style="background-color: #0364af; color: #ffffff;" target="_blank" rel="noopener noreferrer" href="https://github.com/Truiton/PlaceAPIAutocomplete">Source Code</a></p>



<p class="wp-block-paragraph">As you can see the code above, first an instance of GoogleApiClient is created. Further it is set in the adapter as soon as the connection is established using&nbsp;<code>GoogleApiClient.ConnectionCallbacks</code> interface. Next the <code>PlaceArrayAdapter</code> is set using <code>LatLngBounds</code>. A class used for defining latitude and longitude bounds. Here in the Android Places API Autocomplete example above, you can see that I have been using the latitudes and longitudes of Mountain View to set the <code>LatLngBounds</code>. Now to get place details we need to call getPlaceById method in the <code>onItemClick</code> method of <code>AdapterView.OnItemClickListener</code>, which is set while creating the activity. This as a whole would successfully show Google Places API autocomplete predictions in the AutocompleteTextView. But if you would like to use a <a href="http://www.truiton.com/2016/03/android-nearby-places-api-autocomplete-widget/" target="_blank" rel="noopener noreferrer">widget for Autocomplete predictions</a>, refer to this <a href="http://www.truiton.com/2016/03/android-nearby-places-api-autocomplete-widget/" target="_blank" rel="noopener noreferrer">tutorial</a>. Hope this helps. Connect with us on Facebook, Google+ and Twitter for more updates.</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='Mohit Gupt' src='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/a816092ad56645d2635ccfceb9f7e9d44821c19dec126cb394c882ba574eaa04?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://www.truiton.com/author/mohitgupt/" class="vcard author" rel="author"><span class="fn">Mohit Gupt</span></a></div><div class="saboxplugin-desc"><div itemprop="description"><p>Born in New Delhi, India. A software engineer by profession, an android enthusiast and mobile development evangelist. My motive here is to create a group of skilled engineers, who can build better software. Reason being programming is my passion, and also it feels good to make a device do something you want. Professionally I have worked with many software engineering and product development firms. As of now too, I am employed as a senior engineer in a leading tech company. In total I may have worked on more than 20 projects professionally, but whenever I get spare time I share my thoughts here at Truiton.</p>
</div></div><div class="saboxplugin-web "><a href="http://www.truiton.com" target="_self" >www.truiton.com</a></div><div class="clearfix"></div><div class="saboxplugin-socials "><a title="Wordpress" target="_blank" href="https://www.truiton.com/author/mohitgupt/" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-wordpress" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 512 512"><path fill="currentColor" d="M61.7 169.4l101.5 278C92.2 413 43.3 340.2 43.3 256c0-30.9 6.6-60.1 18.4-86.6zm337.9 75.9c0-26.3-9.4-44.5-17.5-58.7-10.8-17.5-20.9-32.4-20.9-49.9 0-19.6 14.8-37.8 35.7-37.8.9 0 1.8.1 2.8.2-37.9-34.7-88.3-55.9-143.7-55.9-74.3 0-139.7 38.1-177.8 95.9 5 .2 9.7.3 13.7.3 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l77.5 230.4L249.8 247l-33.1-90.8c-11.5-.7-22.3-2-22.3-2-11.5-.7-10.1-18.2 1.3-17.5 0 0 35.1 2.7 56 2.7 22.2 0 56.7-2.7 56.7-2.7 11.5-.7 12.8 16.2 1.4 17.5 0 0-11.5 1.3-24.3 2l76.9 228.7 21.2-70.9c9-29.4 16-50.5 16-68.7zm-139.9 29.3l-63.8 185.5c19.1 5.6 39.2 8.7 60.1 8.7 24.8 0 48.5-4.3 70.6-12.1-.6-.9-1.1-1.9-1.5-2.9l-65.4-179.2zm183-120.7c.9 6.8 1.4 14 1.4 21.9 0 21.6-4 45.8-16.2 76.2l-65 187.9C426.2 403 468.7 334.5 468.7 256c0-37-9.4-71.8-26-102.1zM504 256c0 136.8-111.3 248-248 248C119.2 504 8 392.7 8 256 8 119.2 119.2 8 256 8c136.7 0 248 111.2 248 248zm-11.4 0c0-130.5-106.2-236.6-236.6-236.6C125.5 19.4 19.4 125.5 19.4 256S125.6 492.6 256 492.6c130.5 0 236.6-106.1 236.6-236.6z"></path></svg></span></a><a title="Twitter" target="_blank" href="http://twitter.com/mohitgupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-twitter" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 30 30"><path d="M26.37,26l-8.795-12.822l0.015,0.012L25.52,4h-2.65l-6.46,7.48L11.28,4H4.33l8.211,11.971L12.54,15.97L3.88,26h2.65 l7.182-8.322L19.42,26H26.37z M10.23,6l12.34,18h-2.1L8.12,6H10.23z" /></svg></span></a><a title="Facebook" target="_blank" href="https://www.facebook.com/Mr.Mohit.Gupt" rel="nofollow noopener" class="saboxplugin-icon-grey"><svg aria-hidden="true" class="sab-facebook" role="img" xmlns="http://www.w3.org/2000/svg" viewbox="0 0 264 512"><path fill="currentColor" d="M76.7 512V283H0v-91h76.7v-71.7C76.7 42.4 124.3 0 193.8 0c33.3 0 61.9 2.5 70.2 3.6V85h-48.2c-37.8 0-45.1 18-45.1 44.3V192H256l-11.7 91h-73.6v229"></path></svg></span></a></div></div></div><p>The post <a href="https://www.truiton.com/2015/04/android-places-api-autocomplete-getplacebyid/">Android Places API: Autocomplete with getPlaceByID</a> appeared first on <a href="https://www.truiton.com">Truiton</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.truiton.com/2015/04/android-places-api-autocomplete-getplacebyid/feed/</wfw:commentRss>
			<slash:comments>33</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1153</post-id>	</item>
	</channel>
</rss>

<!--
Performance optimized by W3 Total Cache. Learn more: https://www.boldgrid.com/w3-total-cache/?utm_source=w3tc&utm_medium=footer_comment&utm_campaign=free_plugin

Page Caching using Disk: Enhanced 
Minified using Disk

Served from: www.truiton.com @ 2026-08-04 18:00:35 by W3 Total Cache
-->