Some source-code I have inherited sometimes throws a ConcurrentModificationException on this line:
for (String c : filteredList) {
body:
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
ArrayList<String> filteredList = (ArrayList<String>) results.values;
if (results != null && results.count > 0) {
clear();
for (String c : filteredList) {
add(c);
}
notifyDataSetChanged();
}
}
How should I prevent this error from happening?
ConcurrentModificationException:
It is not generally permissible for one thread to modify a Collection while another thread is iterating over it...
A Hotfix solution, would be cloning the ArrayList<String>, before iterate it :
ArrayList<String> filteredList = (ArrayList<String>) results.values.clone();
You need to consider that if the list is large, you're going to consume twice as much RAM during that period of time.
btw, i would run first the validations, before map / clone your list, switching your first 2 lines, as a performance improvement:
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
ArrayList<String> filteredList = (ArrayList<String>) results.values.clone();
clear();
for (String c : filteredList) {
add(c);
}
notifyDataSetChanged();
}
}
Hope it helps! Cheers,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With