2015-11-02 89 views
0

我有一個ArrayList令牌;我使用listView單擊將值添加到數組中。 在我將值添加到數組之前,我檢查該值是否已經存在數組。 我刪除該值是存在別的我將添加值Android檢查值是否等於數組中的值

這是怎麼我都做了,但值沒有被添加到陣列

ArrayList<String> tokens; 
tokens = new ArrayList<String>(); 
... 
.... 
public void onItemClick(AdapterView<?> listView, View view, 
          int position, long id) { 
     Cursor cursor = (Cursor) listView.getItemAtPosition(position); 
     String selectedtoken = cursor.getString(cursor.getColumnIndexOrThrow("ContactToken")); 

     for (int i = 0; i < tokens.size(); i++) { 
       if (tokens.get(i).equals(id_To_Search)) { 
        tokens.remove(i); 
       } 
       else { 
        tokens.add(selectedtoken); 
       } 
      } 
    } 
... 
... 
Log.i("array: ", tokens.toString()); // No values in the array 
+1

我會建議使用一組,然後設定轉換到ArrayList,當你做了,那將是更容易 –

回答

3

您最初沒有加入你的時候有0個令牌。

更改爲:

boolean removed = false; 
for (Iterator<String> iter = tokens.iterator(); iter.hasNext();) { 
    if (iter.next().equals(id_To_Search)) { 
     iter.remove(); 
     removed = true; 
    } 
} 
if(!removed) { 
    tokens.add(selectedtoken); 
} 
+2

這將失敗,並在許多情況下ConcurrentModificationException的。 ..它會*總是*在最後有選定的令牌。 –

+0

我已經更正了第二個但第一個ehhh,它全部在UI線程上 –

+1

僅僅因爲它在一個線程中並不意味着你不會得到'ConcurrentModificationException'。見https://stackoverflow.com/questions/223918 –

2

如果列表是空的,你永遠不會進入死循環,所以你永遠不會打電話add。如果你有任何令牌開始,你要麼爲每個現有的令牌添加或刪除新的令牌這是不是你想要的。

我懷疑你想:

int existingIndex = tokens.indexOf(selectedToken); 
if (existingIndex == -1) { 
    tokens.add(selectedToken); 
} else { 
    tokens.remove(existingIndex); 
} 

或者,你可以使用一個Set<String>有:

// Speculatively try to remove it... and add it if you couldn't remove 
boolean removed = tokens.remove(selectedToken); 
if (!removed) { 
    tokens.add(selectedToken); 
} 

還要注意,目前正在測試用於id_To_Search但隨後加入selectedToken - 這個回答假設你實際上打算在兩個地方使用selectedToken

1

當tokens.size()爲0時,for循環將不會執行。 因此,您永遠不會添加令牌,因爲最初令牌列表爲空。

3

您可以使用contains方法簡單地檢查存在。

if(!tokens.contains(id_To_Search)){ 
    tokens.add(selectedtoken); 
} else { 
    tokens.remove(selectedtoken); 
} 
3

你檢查你的陣列中的每個元素,如果它是你要存儲/刪除,然後做正確操作的項目。

如果你的元素存在於整個數組中,然後添加或刪除它,你應該首先找到它。

嘗試這樣:

public void onItemClick(AdapterView<?> listView, View view, 
         int position, long id) { 
    Cursor cursor = (Cursor) listView.getItemAtPosition(position); 
    String selectedtoken = cursor.getString(cursor.getColumnIndexOrThrow("ContactToken")); 

      if (tokens.contains(id_To_Search)) {  
       tokens.remove(id_To_Search); 

      } 
      else { 
       tokens.add(id_To_Search); 
      } 
}