I have a ArrayList tokens; I am adding values to the array with a listView click. Before i add the value to array i check if the value already exist array. I remove the value is it exists else i will add the the value
This is how i have done, but the values are not being added to the array
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
If your list is empty, you never go into the loop, so you'll never call add
. If you do have any tokens to start with, you're either adding or removing the new token for each existing token which isn't what you want.
I suspect you want:
int existingIndex = tokens.indexOf(selectedToken);
if (existingIndex == -1) {
tokens.add(selectedToken);
} else {
tokens.remove(existingIndex);
}
Alternatively, you could use a Set<String>
with:
// Speculatively try to remove it... and add it if you couldn't remove
boolean removed = tokens.remove(selectedToken);
if (!removed) {
tokens.add(selectedToken);
}
Also note that you're currently testing for id_To_Search
but then adding selectedToken
- this answer assumes you actually meant to use selectedToken
in both places.
See more on this question at Stackoverflow