AutoCompleteTextView OnItemClick position is always "0"

Viewed 12941

the adapter works fine, but i don't understand why the position in OnItemClick is always "0"

String[] regions = ct.getRegions();
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_dropdown_item_1line, regions);
    regionT.setAdapter(adapter);
    regionT.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // TODO Auto-generated method stub
                 int pos=position;
        }
    });
3 Answers

I had the same issue: I couldn't manage to get the position, but I've figured out how to retrieve the whole object selected by the user (if any), having an ID field, which in my case is all I need.
The trick is not to use an ArrayAdapter<String> for the suggested items, but an ArrayAdapter<MyObject>, where MyObject overrides the toString() method.
For instance:

public class Country extends Object {

  public int id;

  public Country(int id) {
    this.id = id;
  }

  @NonNull
  @Override
  public String toString() {
    switch (id) {
      case 0:
        return "Albania";
      case 1:
        return "Romania";
      case 2:
        return "Ucraina";
      case 3:
        return "Russia";
      default:
        return "Unknwon";
    }
  }

}
...
private AutoCompleteTextView mNationAtv;
private Button mTestBtn;
private final Country[] COUNTRIES = {
  new Country(0),
  new Country(1),
  new Country(2),
  new Country(3)
};
...
// use object array for adapter
ArrayAdapter<Country> adapter = new ArrayAdapter<>(this,
  android.R.layout.simple_dropdown_item_1line, COUNTRIES);
mNationAtv.setAdapter(adapter);
mTestBtn.setOnClickListener(new OnClickListener() {

  @Override
  public void onClick(View v) {
    ArrayAdapter<Country> ada = (ArrayAdapter<Country>) mNationAtv.getAdapter();
    int nItems = ada.getCount();
    // default Country unknown
    Country selItem = new Country(5);
    if (nItems > 0) {
      selItem = (Country) ada.getItem(0);
    }
    Log.d(TAG,
        "onClick(): nItems=" + nItems + ", selItem.name=" + selItem.toString()
            + ", selItem.id=" + selItem.id);
  }

});
...

Logs:

  • when the AutocompleteTextView value matches an item in the dropdown:
    onClick(): nItems=1, selItem.name=Ucraina, selItem.id=2

  • when the value is blank:
    onClick(): nItems=4, selItem.name=Albania, selItem.id=0

  • when the value isn't blank but doesn't match any item in the dropdown:
    onClick(): nItems=0, selItem.name=Unknown, selItem.id=5

You might want to fetch this value in the OnItemClickListener()::onItemClick() method, invoked avery time the user clicks an item in the dropdown, or outside of it, i.e. for validation.

Related