1
@Override
public void bleDataReceiverObserver(BluetoothDevice bluetoothDevice) {
    Log.v("bleDataReceiverObserver", bluetoothDevice.getName());
    if (list.size() == 0)
        list.add(new BleData(bluetoothDevice, bluetoothDevice.getAddress(), bluetoothDevice.getName()));
    for (BleData bleData : list) {
        if (bleData.getAddress().equals(bluetoothDevice.getAddress())) {
            break;
        } else
            list.add(new BleData(bluetoothDevice, bluetoothDevice.getAddress(), bluetoothDevice.getName()));
    }
}

Bluetooth scan results are received directly through the receiver. However, the speed of coming in and saving to the list is so fast that exceptions are made. What should I do?

Genie
  • 11
  • 1

4 Answers4

0

From oracle docs

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

When accessing a List item in a loop it's not allowed to edit that list. You are adding item to a list in a loop. If you really need it or you can't find any solution then use another List to add item

Check this thread to learn more.

You can use this code:

  boolean isFound = false;
  for (BleData bleData : list) {
    if (bleData.getAddress().equals(bluetoothDevice.getAddress())) {
        isFound = true;
    }
  } 

  if(!isFound){
       bluetoothDevice.getAddress(), bluetoothDevice.getName()));
  }
Abu Yousuf
  • 5,729
  • 3
  • 31
  • 50
0

Just use CopyOnWriteArrayList instead of ArrayList. The simplest way to solve ConcurrentModificationException.

like this:

List<String> list = new CopyOnWriteArrayList<>();
xingjiu
  • 389
  • 3
  • 6
0

You cannot modify and iterate through same list in for loop. Change your method as follows:

@Override
public void bleDataReceiverObserver(BluetoothDevice bluetoothDevice) {
    Log.v("bleDataReceiverObserver", bluetoothDevice.getName());
    if (list.size() == 0)
        list.add(new BleData(bluetoothDevice, bluetoothDevice.getAddress(), bluetoothDevice.getName()));
    for (BleData bleData : list) {
        if (bleData.getAddress().equals(bluetoothDevice.getAddress())) {
            //Do some action on match
            break;
        } 
    }
}
Sagar
  • 23,903
  • 4
  • 62
  • 62
0

You're iterating through an ArrayList and modifying it at same time. That causes a ConcurrentModificationException, so don't do it.Build a "shadow" copy of the list that has everything you want it to have at the end, then call removeAll() and then addAll(newList) on the original list, and modify new shadow copy in loop

Rahul Chaudhary
  • 1,059
  • 1
  • 6
  • 15