簡體   English   中英

在Android中獲取indexoutofbounds異常

[英]Getting indexoutofbounds exception in android

由於位置從1開始但數組索引從0開始,因此刪除位置時出現了ArrayIndexOutOfBoundsException請問您如何解決這個問題?

if (isChecked && groupName.equals(OLIConstants.FAILED_TO_ACTIVATE))
{
    count = count + 1;
    arrActivation.add(childPosition);
    context.getSummaryFragment().getOli(arrActivation,groupPosition);
    if (!context.getSummaryFragment().activateSystem.isEnabled())
    {
        context.getSummaryFragment().enableButton(true);
    }
}
else if (!isChecked && groupName.equals(OLIConstants.FAILED_TO_ACTIVATE))
{
    count = count - 1;
    arrActivation.remove(childPosition);
}

context.getSummaryFragment().getOli(arrActivation,groupPosition);

if (context.getSummaryFragment().activateSystem.isEnabled() && count <= 0)
{
    context.getSummaryFragment().enableButton(false);
}
}

您可以使用arrActivation.add(childPosition-1);訪問數組arrActivation.add(childPosition-1);

希望這能解決您的問題。

我將根據您的代碼進行假設:

  1. childPosition是您要存儲在ArrayList arrActivation中的數據。

    arrActivation.add(childPosition);

  2. childPosition是一個整數(因為您獲取的數組索引超出了綁定的異常范圍。

    arrActivation.remove(childPosition);

現在,如果您嘗試添加一個整數並使用相同的參數將其刪除,則可能會出現AIOOB異常。 看一看:

    ArrayList here = new ArrayList();
    here.add(5);
    // The following line will exception because
    // The length of the array list is 1 at this point
    here.remove(5);

但這將起作用:

    ArrayList here = new ArrayList();
    here.add(5);
    // The following line will not exception 
    here.remove(Integer.valueOf(5));

因為現在我們使用的是remove(Object o)(使用Object o查找數據,並刪除第一個出現的函數)函數,而不是remove(int index)(試圖刪除arraylist索引的索引)函數。

我希望這有幫助 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM