[英]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.