繁体   English   中英

IndexOutOfBoundsException 索引 0 大小 0 试图编辑填充 arraylist 中的元素

[英]IndexOutOfBoundsException index 0 size 0 trying to edit an element in a populated arraylist

我正在尝试在已填充的 arraylist 中编辑一个元素,但一直收到该错误。 该方法是从片段调用的,但我似乎无法从片段或与片段关联的任何内容访问 arraylist。 在从片段调用的方法中,我可以在相同的 class 中的其他任何地方更改我想要的值。 我将非常感谢提前感谢您的帮助。

片段代码

 MainActivity method = new MainActivity();

@Override
public void onDetach() {
    method.updateQuantity(Quantity);
    super.onDetach();
}

MainActivity 代码

public void updateQuantity(int Quantity){
    items.get(currentitem).setQuantity(Quantity);
}

如果items是您的 ArrayList,那么对于ArrayList.get ,它将integer(index)作为参数,然后返回该索引的元素。

所以,这个items.get(currentitem).setQuantity(Quantity) ) 调用是非常不安全的。 需要先检查最大索引长度,然后再尝试访问它。

public void updateQuantity(int Quantity){
    if(items != null and currentitem < items.size(){
       items.get(currentitem).setQuantity(Quantity);
    }
}

暂无
暂无

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

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