In my Android app I have a ListActivity
which displays bluetooth devices. I have an ArrayList<BluetoothDevice>
and ArrayAdapter<BluetoothDevice>
. Everything works but there is one problem. Each BluetoothDevice
is displayed as a MAC address in the list but I need to display its name.
As I know adapter calls toString
method on each object. But BluetoothDevice
returns MAC address if you call toString
on it. So solution would be to override toString
and return name instead of address. But BluetoothDevice
is final class so I am not able to override it!
Any ideas how to force Bluetooth device to return its name instead address? toString
?
you could use composition instead of inheritance:
public static class MyBluetoothDevice {
BluetoothDevice mDevice;
public MyBluetoothDevice(BluetoothDevice device) {
mDevice = device;
}
public String toString() {
if (mDevice != null) {
return mDevice.getName();
}
// fallback name
return "";
}
}
and off course your ArrayAdapter
, will use MyBluetoothDevice
instead of BluetoothDevice
Once you have your ArrayList
ArrayList<BluetoothDevice> btDeviceArray = new ArrayList<BluetoothDevice>();
ArrayAdapter<String> mArrayAdapter;
Now you can add the devices in the onCreateView for example:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_expandable_list_item_1);
setListAdapter(mArrayAdapter);
Set<BluetoothDevice> pariedDevices = mBluetoothAdapter.getBondedDevices();
if(pariedDevices.size() > 0){
for(BluetoothDevice device : pariedDevices){
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btDeviceArray.add(device);
}
}
So note that you can get the name with the .getName()
method. This solve your problem?
As i already mentioned in the comment you could extend the ArrayAdapter and use another method instead of the toString Method.
For Example like so:
public class YourAdapter extends ArrayAdapter<BluetoothDevice> {
ArrayList<BluetoothDevice> devices;
//other stuff
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//get view and the textView to show the name of the device
textView.setText(devices.get(position).getName());
return view;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.