I want to replace all commas in the display name in a List, how can i do it?
for (int i = 0; i < contacts.size(); i++) {
if(contacts.get(i).getDisplayName().contains(",")){
contacts.get(i).getDisplayName().replace("," , " " );
contacts.notify();
}
}
Well you need to set the display name, I suspect. Currently you're calling String.replace
which creates a new string - but as strings as immutable, the existing display name won't be changed. I suspect you really want:
for (Contact contact : contacts) {
String displayName = contact.getDisplayName();
if (displayName.contains(",")) {
contact.setDisplayName(displayName.replace(",", " ");
contacts.notify();
}
}
Or possibly better (single notification):
boolean anyChanged = false;
for (Contact contact : contacts) {
String displayName = contact.getDisplayName();
if (displayName.contains(",")) {
contact.setDisplayName(displayName.replace(",", " ");
anyChanged = true;
}
}
if (anyChanged) {
contacts.notify();
}
Note how unless you're using a list index for something other than getting the value out of the list, your code is cleaner if you use an enhanced for loop as above.
See more on this question at Stackoverflow