【问题标题】:Android get selected item position from Class structure in AutoCompleteAndroid从AutoComplete中的类结构中获取选定的项目位置
【发布时间】:2015-05-01 08:38:45
【问题描述】:

我正在尝试从 AutoComplete 中查找作为 ArrayList 的类结构位置,例如我有这样的类结构:

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,大小为 0 在 java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251) 在 java.util.ArrayList.get(ArrayList.java:304)

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

例如:

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

结果是:POS: Item 1)

【问题讨论】:

  • 只对。列表中什么都没有,那么它将如何显示??
  • @Shadow 帖子已更新,请检查先生,
  • 你在哪里插入数据?
  • @Shadow in bakcground and customersList.size(); is 3
  • 尝试在 setOnItemClickListener 中记录大小。它返回什么?

标签: java android


【解决方案1】:

这里你的列表是空的,你正试图从中获取数据。

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

喜欢:

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

}

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

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

【讨论】:

  • 我的数组列表不是空的,我有 3 个项目,我没有任何问题来获取选定的文本,我只想获取选定的位置而不是选定的文本先生,
  • 查看您发布的错误消息,上面写着Invalid index 0, size is 0。 arraylist 的大小为 0 请再次检查代码您使用的是空列表
  • 是的,先生。当我尝试获取位置时出现此错误
  • 对不起先生。我的小部件是AutoComplete 我忘了说
  • onItemClick方法中使用日志语句
【解决方案2】:

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

表示你的数组列表,customersList 为空,你想在位置 0 获取项目,这是无效的。因此首先检查 customersList 长度为

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-03
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    相关资源
    最近更新 更多