Tombola
Tombola

Reputation: 1141

Why is BluetoothDevice sometimes a string?

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!

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.

Upvotes: 0

Views: 1022

Answers (2)

ksu
ksu

Reputation: 902

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();

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 181057

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.

Upvotes: 2

Related Questions