Is it possible to load ListPreference items from an adapter? Is it possible to load ListPreference items from an adapter? arrays arrays

Is it possible to load ListPreference items from an adapter?


For the special case of a list of bluetooth devices, you can use the following class:

package de.duenndns;import android.bluetooth.*;import android.content.Context;import android.preference.ListPreference;import android.util.AttributeSet;import java.util.Set;public class BluetoothDevicePreference extends ListPreference {    public BluetoothDevicePreference(Context context, AttributeSet attrs) {        super(context, attrs);        BluetoothAdapter bta = BluetoothAdapter.getDefaultAdapter();        Set<BluetoothDevice> pairedDevices = bta.getBondedDevices();        CharSequence[] entries = new CharSequence[pairedDevices.size()];        CharSequence[] entryValues = new CharSequence[pairedDevices.size()];        int i = 0;        for (BluetoothDevice dev : pairedDevices) {            entries[i] = dev.getName();            if (entries[i] == null) entries[i] = "unknown";            entryValues[i] = dev.getAddress();            i++;        }        setEntries(entries);        setEntryValues(entryValues);    }    public BluetoothDevicePreference(Context context) {        this(context, null);    }}

It can be involved directly from your prefs XML to store the MAC as a prefs string:

<de.duenndns.BluetoothDevicePreference    android:key="bluetooth_mac"    android:title="Bluetooth Device"    android:dialogTitle="Choose Bluetooth Device" />


ListPreference doesn't work with adapters, it works with strings. See setEntries() and setEntryValues()

To get at your ListPreference, call findPreference() on your PreferenceActivity. Cast the Preference you get back to ListPreference.


Just an Update to this in case someone else comes along, ge0rg answer works but changed it a little to take in consideration of multiple preferences and not just the bluetooth one and also if they dont have any paired devices set up so you dont get an error with a null array.

ListPreference BTList = (ListPreference) findPreference("your preference key");    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();    CharSequence[] entries = new CharSequence[1];    CharSequence[] entryValues = new CharSequence[1];    entries[0] = "No Devices";    entryValues[0] = "";    if(pairedDevices.size() > 0){        entries = new CharSequence[pairedDevices.size()];        entryValues = new CharSequence[pairedDevices.size()];        int i=0;        for(BluetoothDevice device : pairedDevices){            entries[i] = device.getName();            entryValues[i] = device.getAddress();            i++;        }    }    BTList.setEntries(entries);    BTList.setEntryValues(entryValues);

`Hope this helps someone...oh and this is put under the onCreate method for the preference activity