2015-11-02 90 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); 
      } 
}