繁体   English   中英

Android从AutoComplete中的Class结构中获取选定项的位置

[英]Android get selected item position from Class structure in AutoComplete

我试图从AutoComplete的ArrayList中找到Class结构的位置,例如,我有这个class结构:

public class Clients {

    @DatabaseField(generatedId = true)
    public int id;

    @DatabaseField
    public int client_code;

    public int getClient_code() {
        return client_code;
    }
}

我从此类定义ArrayList为:

private ArrayList<Clients> customersList = new ArrayList<Clients>();

现在我有一些数据到这个arrayList中,我想获得选择的位置以找到选择了哪个client_code

at_sender_package.setOnItemClickListener(new AdapterView.OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
        int selectedposition=position;
        Log.e("SELECTED ITEM: ", customersList.get(selectedposition).getClient_code()+"");
    }
});

不幸的是我得到这个错误:

java.lang.IndexOutOfBoundsException:无效的索引0,在java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)的大小为0,在java.util.ArrayList.get(ArrayList.java:304)

我的数组列表不为空,我有3个项目,我没有任何问题来获取所选文本,我只想获取所选位置而不是所选文本

例如 :

Log.e("POS: ", parent.getItemAtPosition(position) + "");

结果是: POS: Item 1)

在这里,您的列表为空,您正在尝试从中获取数据。

避免此错误的主动方法是在使用列表元素之前对列表长度进行一次检查。

喜欢 :

if(customersList.size() > 0) {
//do your stuff

}

您可以在此处阅读有关此错误的更多信息:

http://voidexception.weebly.com/array-index-out-of-bounds-exception.html

java.lang.IndexOutOfBoundsException:无效的索引0,大小为0

表示您的arraylist, customersList为空,并且您想要在位置0处获得无效的项目,因此首先检查customersList长度为

if (customersList.size() > 0) {
    Log.e("SELECTED ITEM: ", customersList.get(selectedposition).getClient_code() + "");
} else {
    Log.e("SELECTED ITEM: ", "customersList is empty");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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