AutoCompleteTextView in Android

We mostly use search engines like Google for finding anything on the internet.  Doing that you might have noticed that as we start typing , a number of  suggestions drops down. An AutoCompleteTextView works in a similar fashion.

Now, let’s see how this can be implemented in android.

Firstly, let’s look at the XML layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" > 
    <AutoCompleteTextView
        android:id="@+id/autotv"
        android:layout_width="300dip"
        android:layout_height="wrap_content"
        />
</LinearLayout>

I’ve stored the data for the AutoCompleteTextView  in the String Array named AndroidDesk in an XML file named strings.xml in the res/values folder in my project.

Note: You can also create a String Array in your Activity instead.

The strings.xml file is:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, MyAutoCompleteTextViewActivity!</string>
    <string name="app_name">MyAutoCompleteTextView</string>
    <string-array name="AndroidDesk">
    <item >Top Posts </item>
    <item>Activity in android by Deepthi</item>
    <item >Implicit Intent by Deepthi</item>
    <item >Custom Dialog in Android by Deepthi</item>
    <item >Custom Toast in Android by Deepthi</item>
    <item >Creating Progess Dialog in Android by Deepthi</item>
    <item >Check the usage of Checkbox in Android Activity by Deepthi</item>
    <item >Introducing Android by Deepthi</item>
    <item >Button in Android by Deepthi</item>
    </string-array>
</resources>

The data is provided to the AutoCompleteTextView through an array adapter.

final String[] AndroidDesk= getResources().getStringArray(R.array.AndroidDesk);
 ArrayAdapter<String> My_arr_adapter= new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1line,AndroidDesk);

Now I need to create a reference to the AutoCompleteTextView  and then set the adapter.

AutoCompleteTextView My_auto_Cmplt_Tv=(AutoCompleteTextView)findViewById(R.id.autotv);
My_auto_Cmplt_Tv.setThreshold(2);
My_auto_Cmplt_Tv.setAdapter(My_arr_adapter);

Here, setThreshold(2) method is used to make the suggestions appear only after typing two letters of what the user desires. Hope I made it clear. :) If not, don’t worry you will understand it better as you go through the screen shots given at the end.

Now, let’s toast a notification telling what we have clicked in the list of suggestions obtained.

The code for doing that is:

My_auto_Cmplt_Tv.setOnItemClickListener(new OnItemClickListener() {
 public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),(CharSequence)arg0.getItemAtPosition(arg2), Toast.LENGTH_LONG).show();
                        }
                });

Now , have look at the Whole code:

package com.deepthi.autocompletetextview;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;
 public class MyAutoCompleteTextViewActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final String[] AndroidDesk= getResources().getStringArray(R.array.AndroidDesk);
        ArrayAdapter<String> My_arr_adapter= new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_dropdown_item_1line,AndroidDesk);
        AutoCompleteTextView My_auto_Cmplt_Tv=(AutoCompleteTextView)findViewById(R.id.autotv);
        My_auto_Cmplt_Tv.setThreshold(2);
        My_auto_Cmplt_Tv.setAdapter(My_arr_adapter);
        My_auto_Cmplt_Tv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
                                // TODO Auto-generated method stub
 Toast.makeText(getApplicationContext(),(CharSequence)arg0.getItemAtPosition(arg2), Toast.LENGTH_LONG).show();
                        }
                });
    }
}

The Output is shown below:

As the user types at least two letters: 

As the user clicks one of the suggestions in the list:

About these ads

, , , , , ,

  1. #1 by Gautam M. on March 21, 2012 - 10:23 pm

    Hello Deepthi,
    Thankyou for this useful post it works like a charm. Well I am using it a bit differently in my app. The values in my adapter come from my DB table depending on what the user inputs in the edittext. I am able to show the autocomplete and it works perfectly when I select the first item in the list. An indexOutofBounds exception( Invalid index 1, size is 1) is thrown if I select the 2nd item and so on. I am annoyed with this exception since Im not able to figure it out. Please if you can,help me clear my problem. This is the onItemClick(),

    edittext.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
    public void onItemClick(AdapterView arg0, View arg1, int arg2,
    long arg3) {
    ArrayAdapter a = (ArrayAdapter)arg0.getAdapter();
    String FullName = (String)a.getItem(arg2);
    FetchFromDB(FullName,2);
    }
    });

    Thanking You,
    Gautam M.

  2. #2 by Deepthi G on March 22, 2012 - 10:07 am

    Hey Gautam,

    Thanks a lot for reading my blog and I’m happy to hear that my post was useful to you.. Well, I’m a newbie in android and only started working with DB.But I’ll try my best to help you out. :)
    IndexOutofBounds exception occurs when the user tries to get element beyond the capacity of the index.. Just check this link:

    http://www.roseindia.net/java/java-exception/index-out-bound-exception.shtml

    With this small piece of code that you have shared, I can just guess the issue.
    Let me just guess.
    ‘edittext’ could be the reference to EditText in your app right?
    To my knowledge onItemClick() is used to click items when there a more than one item in a view. So hope, you need to click item from the autocompletetextview.. Hope you got what I’m trying to say.
    Just check this link too :

    http://developer.android.com/guide/topics/ui/binding.html

    Do let me know if your issue is solved. :)

    • #3 by Gautam M. on March 22, 2012 - 1:05 pm

      Good Morning Deepthi,
      Thankyou for those useful links. Well after struggling with my code, I was able to solve my issue. Ill tell you how. See Ive implemented the autocomplete feature by having my own class CustomAutoComplete extends AutoCompleteTextView. Now there are three methods that you really need to consider while implementing autocomplte feature.
      1) afterTextChanged(Editable s);
      2) beforeTextChanged(CharSequence s, int start, int count, int after);
      3) onTextChanged(CharSequence s, int start, int before, int count);

      Each of them having their own importance, but 1st and 3rd method are of a concern to us.

      –>Whenever user types in the EditText, the length of the input is determined by the 1st method by the (Editable s) parameter. This is where you can manipulate with the input, like what values the adapter should contain for the autocomplete dropdown list.

      –>Whenever user select a particular item from the drop down, the 3rd method acts as a culprit. Let say in the 1st method your adapter contains 5items for the dropdown list for the user input. On selecting a particular item,the onTextChanged() method is called,the adapter is erased and filled with the item you selected. This works fine if you select first item, but IndexOutofBounds is raised if you select item 2,3,4,5. Reason being,in the 1st method adapter contains 5items, but after item selection adapter contains 1item only, due to our dear 3rd method. And you know how IndexOutofBounds works.

      –>So now the solution is write the onTextChanged method as follows (which is self explanatory):-

      public void onTextChanged(CharSequence s, int start, int before, int count)
      {
      String input = edittext.getText().toString(); // user input

      if(input.length() > 0)
      {
      adapter.clear();
      adapter.add(input);
      }
      edittext.setAdapter(adapter); // set new adapter value to our autocompltetextview
      }

      –> And now change the onItemClick() to
      edittext.setOnItemClickListener(new AdapterView.OnItemClickListener()
      {
      public void onItemClick(AdapterView arg0, View arg1, int arg2,long arg3)
      {
      String FullName = adapter.getItem(0); //gets the item user clicked upon
      FetchFromDB(FullName,1); // your calculation goes here
      }
      });

      Now no matter whichever item you click this will definitely work.
      Huusssh!!! Hope this makes you gain some knowledge in android. Well nice to meet you!!!

      Thanking you ,
      Gautam M.

  3. #4 by Deepthi G on March 22, 2012 - 2:41 pm

    Hey Gautam..

    Really glad to hear that you solved you issue.. As you have only shared a few of your code it was difficult for me to find out the mistake.. Happy that you found those links useful.. :)

    • #5 by Gautam M. on March 22, 2012 - 2:45 pm

      Yeah thanks.. Looking forward to go through some more useful posts in your blog.

      Thanks,
      Gautam M.

      • #6 by Deepthi G on March 22, 2012 - 3:43 pm

        Hey Gautam..

        You are Welcome..:) Keep reading buddy.. :) And Do share your issues and suggestions too…:)

        Regards
        Deepthi.G

  4. #7 by koushik on September 4, 2012 - 5:45 pm

    Thank u very much Deepthi for posting the usuage of auto complete box……

    It will be useful for me…..

    is there anything like autocomplete box should search in web and display results….

    ex:if i search like big bazar……

    the auto complete should show the results like

    big bazar abids
    big bazar himath nagar
    big bazar hyderabad
    big bazar pune

    can u help me out deepthi ……thanks in advance…

  5. #8 by Murugan on September 20, 2012 - 4:49 pm

    deepthi….really nice tutorial…your concepts are beautiful as you are….

  6. #9 by jay on December 5, 2012 - 4:45 pm

    Hi super..

  7. #10 by MyAndroidAppStore on December 6, 2012 - 2:20 pm

    Hi Deepthi

    How can i change Activity using AutoTextComplete

  8. #11 by Brijesh on March 26, 2013 - 11:49 am

    how to create custom AutoCompleteTextView in android with two textview in AutoCompleteTextView row..

  9. #12 by surekha on March 28, 2013 - 9:47 am

    Hey Deepthi,
    Thanks a lot to share this blog, i got an idea as to where string-array has to be and how to call that in our activity class. This helped me a lot for my project.

  10. #13 by Ashita Ranjan on July 30, 2013 - 12:30 pm

    Thanks for sharing those blogs. its pretty much helpful for me

  11. #14 by Ambuj Rajput on October 13, 2013 - 3:38 pm

    short and easy……………

  12. #15 by nikhil on November 6, 2013 - 11:36 am

    Thanks lot… wasted much time on it…

  13. #16 by Nikhil on January 8, 2014 - 2:13 pm

    please tell me how to check autocompletetextview empty or not ?

  14. #17 by Amol on January 17, 2014 - 2:40 pm

    hey hi
    Thank a lot but i have same problem .when you type ‘cu’ and 2 suggestion is drop dawn i want to display total list string like
    “Custom Dialog in Android by Deepthi”
    “Custom Toast in Android by Deepthi”
    without hide any character

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: