简体   繁体   中英

Android AutoCompleteTextView: get item position

I'm creating a custom class in which I associate a Cursor (populated with values extracted from a SQLite database) to an AutoCompleteTextView , with an ArrayAdapter . Each record extracted from Cursor is represented by an ID and a value , and it's added to an ArrayAdapter by value. While adding values, I also create two ArrayList to keep track of both IDs and values.

I'd like to be able to get selected item position , but I actually cannot do it, even with onItemClick Listener.

Here it is some code from my custom class:

private AutoCompleteTextView field;
private String column;
private Activity activity;
private ArrayList<String> list_id, list_values;

//Constructor
public PopulateAutoComplete(int elementFromLayout, String column, Activity activity) {
    this.field = (AutoCompleteTextView) activity.findViewById(elementFromLayout);
    this.activity = activity;
    this.column = column;
}
//Reset two lists associated to actual element
private void initializeLists() {
    list_id= new ArrayList<>();
    list_values= new ArrayList<>();
}
//Populating methods
public void populate(Cursor cursor_total, String column_id, String column_values) {
    initializeLists();
    int i=0;
    String id = null;
    String value = null;
    cursor_total.moveToFirst();
    do {
        id = cursor_total.getString(cursor_total.getColumnIndex(column_id));
        value = cursor_total.getString(cursor_total.getColumnIndex(column_values));
        list_id.add(i,id);
        list_values.add(i,value);
        i++;
    } while (cursor_total.moveToNext());
    adapter = new ArrayAdapter<>(activity,android.R.layout.simple_dropdown_item_1line, list_values);
    field.setAdapter(adapter);
}
//Method which select the right item from the list
public void selectValue(Cursor cursor_single, String column_value_to_select) {
    String id_to_verify = cursor_single.getString(cursor_single.getColumnIndex(column_value_to_select);
    loop: {
        for (int i=0; i<listaID.size(); i++) {
            if (list_id.get(i).equals(id_to_verify)) {
                adapter.getItem(i);
                field.setText(list_values.get(i));
                break loop;
            }
        }
    }
    setListener();
}
private void setListener() {
    field.setOnItemClickListener(listener);
}
private AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        //How to get ID of selected item here?
    }
};

And here it's the code from my MainActivity :

PopulateAutoComplete element = new PopulateAutoComplete(R.id.element, "column", this);
element.populate(cursor,"id","name");
element.selectValue(cursor_single,"id");

I'd like to have the ID of selected item, so I can use list_id.getItem(position) .

I tried with field.getListSelection() , list_id.indexOf(adapterView.getSelectedItem()) but it was not helpful. I also know that some of this method are related to actual dropdown list, but I need a method which extract the exact position of an item in the ArrayAdapter; in this way, I can automatically extract ID and values (note: values are not unique).

EDIT #1:

public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        adapterView.getSelectedItemPosition();   //It returns "-1"
        i;  //It returns a result depending on actual shown dropdown list. If I have a list of 200 item and I have 1 item shown on the dropdown, position will be always 0
    }
};

This is my final solution . Thanks pskink for your support.

Methods for AutoCompleteTextView custom class:

//1) Insert all the elements into the AutoCompleteTextView
public void populate(String tag, String column_shown) {
    this.TAG = tag;  //I use a tag in order to differentiate queries I need to execute
    this.column_value =column_shown;
    String[] from = {column_shown};
    int[] to = {android.R.id.text1};
    cursorAdapter = new SimpleCursorAdapter(activity, android.R.layout.simple_dropdown_item_1line, null, from ,to, 0);
    setSearchFilter();
    cursorAdapter.setStringConversionColumn(1);
    field.setAdapter(cursorAdapter);
}
//2) Specify which query to use during the auto-complete step (while typing)
private void setSearchFilter() {
    FilterQueryProvider provider = new FilterQueryProvider() {
        @Override
        public Cursor runQuery(CharSequence constraint) {
            System.out.println("PAC - runQuery: " + constraint);
            if (TextUtils.isEmpty(constraint)) {
                return null;
            }
            String[] params = {"%" + constraint.toString() + "%"};
            //Different queries for different tags
            switch (TAG) {
                case ("report"): {
                    Cursor c = db.getReport(column_value, params);
                    //db is an istance of a Custom Class for SQLiteDatabase
                    return c;
                }
            }
            return null;
        }
    };
    cursorAdapter.setFilterQueryProvider(provider);
}
//3) Method to select the correct value while loading Activity for the first time. The value is taken from DB
public void selectValue(Cursor c) {
    if (c==null) {
        return;
    }
    if (c.getCount()==0) {
        return;
    }
    String id_to_verify = c.getString(c.getColumnIndex(column_id));
    setID(id_to_verify);  //I need this to take memory of actual record ID
    field.setText(c.getString(c.getColumnIndex(column_value)));  //field is an instance of AutoCompleteTextView custom class
}

Methods for SQLiteDatabase custom class. This was the important part for my issue: I need to specify an _id column inside my query to get methods working.

public Cursor getReport(String column, String params[]) {
    String query = "SELECT id AS _id, name FROM customers WHERE " + column + " LIKE ? ORDER BY name ASC;";
    return db.rawQuery(query,params);
}

Methods for MainActivity :

private PopulateAutoComplete customer;
@Override
protected void onCreate(Bundle savedInstanceState) {
    //...
    Cursor cursorCustomer = `...`;  //Used to find actual value on Activity loading
    customer = new PopulateAutoComplete(R.id.customer,"id_customer",db,this);
    customer.populate("report", "name");
    customer.selectValue(cursorCustomer);
}

Try the solution here. I assume the same value can't appear twice in the data list (for example, you can't have "item1" twice in list_values:

how to find the position of item in a AutoCompletetextview filled with Array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM