Search code examples
androidarrayslistautocompletetextview

How to handle Autocomplete Textview item selection?


I'm using autocomplete to show a list of dogs from database.

Suppose I have a DogList with 3 objects: Dog1,Dog2,Dog3 and a String array "dogNames" with each name of these dogs (I'm fetching autocomplete adapter with this array).

When an item is selected while full list is shown I can handle which dog was selected by getting it from DogList using autocomplete selected index, since "DogList" and "dogNames" array have the same size:

    Dog newDog = new Dog();

    autoComplete_dogs.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            newDog = dogList.get(i);



        }

The problem is when I type Dog3 and click it, selected index is 0, which gives Dog1 but not Dog3, since Dog1 has index 0 in DogList.

How should I dinamically sort DogList so it follows autocomplete result list, and every time I try to get a dog from DogList using autocomplete index I get the right object?


Solution

  • In your onItemClick method use this

    newDog = adapterView.getItemAtPosition(i);