Android AutoCompleteTextView:获取料品位置

时间:2015-10-02 08:02:27

标签: java android sqlite position autocompletetextview

我正在创建一个自定义类,我将 Cursor (填充了从SQLite数据库中提取的值)与 AutoCompleteTextView 关联,并使用 ArrayAdapter 即可。 从Cursor中提取的每条记录都由 ID 表示,并且它按值添加到ArrayAdapter。在添加值时,我还创建了两个ArrayList来跟踪ID和值。

我希望能够选择项目位置,但实际上我无法做到,即使使用onItemClick Listener也是如此。

这是我的自定义类中的一些代码:

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?
    }
};

这是我的 MainActivity 的代码:

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

我想拥有所选项目的ID,因此我可以使用 list_id.getItem(position)

我尝试使用 field.getListSelection() list_id.indexOf(adapterView.getSelectedItem()),但它没有帮助。 我也知道这个方法中的一些与实际的下拉列表有关,但我需要一个方法来提取ArrayAdapter中项的确切位置;通过这种方式,我可以自动提取ID和值(注意:值不是唯一的)。

编辑#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
    }
};

2 个答案:

答案 0 :(得分:0)

这是我的最终解决方案。感谢 pskink 的支持。

AutoCompleteTextView自定义类的方法:

//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
}

SQLiteDatabase自定义类的方法。这是我的问题的重要部分:我需要在查询中指定 _id 列以使方法正常工作。

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);
}

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);
}

答案 1 :(得分:-1)

在此尝试解决方案。我假设相同的值不能在数据列表中出现两次(例如,在list_values中不能有两次“item1”:

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