0

I'm trying to receive all available sensors on the system and sort them alphabetic according sensor name.

I'm using Collections and Comparator as I found in this answer but I get UnsupportedOperationException error.

The code:

SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
List<Sensor> sensorList = sensorManager.getSensorList(Sensor.TYPE_ALL);
Collections.sort(sensorList, new Comparator<Sensor>() {
    @Override
    public int compare(Sensor leftSensor, Sensor rightSensor) {
        return leftSensor.getName().compareTo(rightSensor.getName());
    }
});

The questions, why I got this error?

Community
  • 1
  • 1
AsfK
  • 3,328
  • 4
  • 36
  • 73

1 Answers1

2

As you can see in the source code (I know this is some old source code, but that will do), the returned list is immutable.

A fix would be to copy the list:

List<Sensor> sensorList = new ArrayList<Sensor>(sensorManager.getSensorList(Sensor.TYPE_ALL));