2014-02-21 75 views
-1

我有這樣的代碼無效指數0,大小爲0無法添加到ArrayList中

ArrayList<File> internalPaths = new ArrayList<File>(); 
ArrayList<File> externalPaths = new ArrayList<File>(); 

for (int i = 0; i < pathCounter; i++) { 

    Log.e("PK", Integer.toString(pathCounter)); 
    if (i == 0) { 
     // first path 
     String path = pathString.substring(commaPositions[i], 
      commaPositions[i + 1] + 1); 

     if (path.length() > 7 && path.substring(0,8).contains("storage")) { 
      externalPaths.add(new File(path)); 
     } else { 
      internalPaths.add(new File(path)); 
     } 
    } 
} 

它正好沒有在部分

else { 
    internalPaths.add(new File(path)); 
} 

,出現異常:

無效索引0,大小爲0.

我不知道這是如何可能的,因爲我沒有問題,增加到externalPaths,但與internalPaths有這個錯誤。

+0

你如何聲明commaPositions? –

+0

你確定你的代碼是最新的。你能確定錯誤的準確路線,而不是阻斷嗎? –

+0

對不起,編輯。現在更清楚了。 – PetoU

回答

0
if (path.length() > 7 
         && path.substring(0,8).contains("storage")) { 

0,8的子串索引可能會導致字符串短於8個字符的問題。你也可能需要處理空弦的情況。

+0

'substring()'調用在長度爲7的「String」上不會引起任何問題,因爲第二個參數是獨佔的。 – bcsb1001

1

它恰好沒有上部分

else { 
    internalPaths.add(new File(path)); 
} 

InternalPaths是被初始化一個ArrayList(未一個NullPointerException)及其add方法假設在陣列的端部追加的項目和而不是put它在一個特定的地方(索引位置)。因此,問題應該在File的構造函數中。調試並檢查path的值。我敢打賭這是一個空的字符串。弄清楚它如何被初始化爲這樣的價值。

相關問題