[英]IndexOutOfBoundsException index 0 size 0 trying to edit an element in a populated arraylist
I am trying to edit an element in an already populated arraylist but keep getting that error.我正在尝试在已填充的 arraylist 中编辑一个元素,但一直收到该错误。 The method is called from a fragment but I can't seem to access the arraylist from the fragment or Anything the fragment is associated with.该方法是从片段调用的,但我似乎无法从片段或与片段关联的任何内容访问 arraylist。 I can change the value I want anywhere else in the same class expect in that method which is called from the fragment.在从片段调用的方法中,我可以在相同的 class 中的其他任何地方更改我想要的值。 I will really appreciate the help thanks in advance.我将非常感谢提前感谢您的帮助。
Fragment Code片段代码
MainActivity method = new MainActivity();
@Override
public void onDetach() {
method.updateQuantity(Quantity);
super.onDetach();
}
MainActivity code MainActivity 代码
public void updateQuantity(int Quantity){
items.get(currentitem).setQuantity(Quantity);
}
If items
is your ArrayList, then for ArrayList.get
, it takes integer(index)
as an argument and then returns the element of that index.如果items
是您的 ArrayList,那么对于ArrayList.get
,它将integer(index)
作为参数,然后返回该索引的元素。
So, this items.get(currentitem).setQuantity(Quantity)
) call is very unsafe.所以,这个items.get(currentitem).setQuantity(Quantity)
) 调用是非常不安全的。 Need to check the max index length first then try to access it.需要先检查最大索引长度,然后再尝试访问它。
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.