Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentModificationException inside PublishResult - ArrayAdapter

Tags:

java

android

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?

like image 623
Tim Nuwin Avatar asked Aug 26 '26 01:08

Tim Nuwin


1 Answers

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,

like image 73
Tom Avatar answered Aug 27 '26 14:08

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!