0

What type is BluetoothDevice??? In this code, device works like a string (holding the UUID of the physical device) when i use it in Log() for LogCat. But I cannot assign it to a string variable (Eclipse complains that it is of type BluetoothDevice).

String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.v(TAG, "Device="+device); //DISPLAYS "Device=58:17:1C:EB:E3:A8" IN LOGCAT
String d = device; // TYPE MISMATCH!
  • How come a BluetoothDevice object is displayed by its UUID in LogCat, as if it were a string?

EDIT: The getName() crash was caused by BluetoothDevice returning null first time, because I receive ACTION_DISCOVERY_STARTED from BluetoothAdapter. So that is solved. The mystery of why BluetoothDevice sometimes is a String remains.

Tombola
  • 1,131
  • 5
  • 15
  • 26

2 Answers2

2

The reason it shows in the log is that it implements toString() (more info here) which allows it to be automatically converted to a string for logging.

If you want the hardware address as a string to use in your logic, you should use device.getAddress instead, which is in a format that is less likely to change.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
  • Okay, but what determines that it is the address field, of all fields in BluetoothDevice, which is used by toString()? Can I determine what field of an object should be used default by object.toString? – Tombola Mar 02 '12 at 12:50
  • @Tombola When you implement your own classes, you can decide for yourself by implementing toString(), with system classes like this it may be a hassle to extend/override just to change that. I generally end up creating a static Debug class with members that take for example a BlueTooth device and return the string I want, then call Log.v(Debug.btDeviceAsString(device)) to log it. Not beautiful, but workable and less hassle than extending every class I want a custom format for. I'm pretty sure there are better ways though, suggestions welcome :) – Joachim Isaksson Mar 02 '12 at 13:01
0

the device that you get is not a string but an instance of the BluetoothDevice.
If you want the name of this bluetooth device, you can use:

device.getName(); //returns the string representation of this bluetooth

Interestingly, when you use ArrayList<BluetoothDevice> as one of the inputs of ListView, the output in the list is the MAC address, not UUID as you suggested.

If you want the UUID, you can use:

uuid = device.getUuids()[0].getUuid();
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
ksu
  • 882
  • 1
  • 11
  • 17