Christos Baziotis
Christos Baziotis

Reputation: 6035

Android AutoCompleteTextView with List<String>

I have an AutoCompleteTextView where the user types an address. I want to be able to show suggestions below as he types. To do that I get a list of possible addresses via the Reverse Geocoding API. i want then to show this list of strings (possible addresses) to the user. Just like the google maps app does.

I have added a TextChangedListener to the AutoCompleteTextView. On the onTextChanged() event an AsyncTask is executed where the list of possible address gets updated on the onPostExecute().

autoText.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        new GeoTask().execute();
    }
});

Attempt 1

This is the list:

static List<String> suggestionList = new ArrayList<String>();

And this is the code for the adapter for the AutoCompleteTextView :

autoText.setThreshold(3);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, suggestionList);
autoText.setAdapter(adapter);
adapter.setNotifyOnChange(true);

With the above code nothing shows up.

Attempt 2

I also tried using an array as an argument for the adapter and every time the list of address gets updated I convert it to the array.

static String[] suggestions;
static List<String> suggestionList = new ArrayList<String>();

Adapter:

autoText.setThreshold(3);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, suggestionList);
autoText.setAdapter(adapter);
adapter.setNotifyOnChange(true);

AsyncTask:

protected void onPostExecute(Void aVoid) {
...
suggestions = suggestionList.toArray(new String[suggestionList.size()]);
super.onPostExecute(aVoid);
}

How can i make it work? Is there a way to use the adapter with the list?

Upvotes: 1

Views: 4903

Answers (1)

Desert
Desert

Reputation: 2303

The reason why nothing shows up is because the list is empty and in onPostExecute of your AsyncTask your only assigning new array to your suggestions reference, what you should really do is use adapters methods to add and remove elements. You can try this code:

adapter.clear();
adapter.addAll(/*new collection of suggestions*/);

in your onPostExecute method.

NOTE: adapter.addAll() method appeared only from 11th API, so if you use lower, then you would have to add each item manually.

Upvotes: 1

Related Questions