Search code examples
androidlistviewandroid-listviewandroid-sensors

Error in listview name sensors android


I'm trying to display only the name of sensors in my listview.. In the log i can do it but in my listview not:

 mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);

    for(Sensor s : deviceSensors) {
        Log.d("SENSORS", s.getName());
        listView.setAdapter(new ArrayAdapter<Sensor>(this,
                R.layout.customlistview, deviceSensors);
    }

In this way i can display the names in the log my in the listview appears every information about sensors and not only the name. If i try in this way:

 mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);

    for(Sensor s : deviceSensors) {
        Log.d("SENSORS", s.getName());
        listView.setAdapter(new ArrayAdapter<Sensor>(this,
                R.layout.customlistview, s.getName()));
    }

It gets me error in listview: The constructor ArrayAdapter<Sensor>(SensorsActivity, int, String) is undefined how can i solve?


Solution

  • The log works because you're printing the name of every single sensor in it. Adapters just work different. You need one Adapter for the whole list view. Then, when you want to show more then just one text, e.g. sensor name and vendor, you must also override the getView() method in the Adapter. In there you handle all the settings for one line in the list view.

    Lets start with the simple way of just the sensor name in each line of the list view:

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    deviceSensors = mSensorManager.getSensorList(Sensor.TYPE_ALL);
    ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.customlistview));
    listView.setAdapter(adapter);
    
    for(Sensor s : deviceSensors) {
        Log.d("SENSORS", s.getName());
        adapter.add(s.getName());
    }
    

    Your R.layout.customlistview must contain a single TextView that is used to show the given string (sensor name).