dejanualex
dejanualex

Reputation: 4328

Android Studio Bluetooth application

I am making a small application, in which the phone connects automatically using Bluetooth protocol to a certain device, so basically I am trying to do this:

This is the event generated when the user taps on the list:

public void onItemClick(AdapterView adapterView, View view, int i, long l) {
        //first cancel discovery because its very memory intensive.
        mBluetoothAdapter.cancelDiscovery();

        Log.d(TAG, "onItemClick: You Clicked on a device.");
        String deviceName = mBTDevices.get(i).getName();
        String deviceAddress = mBTDevices.get(i).getAddress();

        Log.d(TAG, "onItemClick: deviceName = " + deviceName);
        Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress); 

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2) {
            Log.d(TAG, "Trying to pair with " + deviceName);
            for (BluetoothDevice device: mBTDevices){
                if (device.equals("HTC")){
                    device.createBond();
                }
            }

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
    private static final String TAG = "MainActivity";

    BluetoothAdapter mBluetoothAdapter;
    Button btnEnableDisable_Discoverable;

    public ArrayList mBTDevices = new ArrayList();

    public DeviceListAdapter mDeviceListAdapter;

    ListView lvNewDevices;

My question is, where am I mistaking?

for (BluetoothDevice device: mBTDevices){
    if (device.equals("HTC")){
        device.createBond();

Because the application does not behave as expected. More precisely when I tap on a device from the list I would like to automatically create a bond with the device that has the name "HTC", instead nothing happens.

Upvotes: 1

Views: 657

Answers (1)

Iakovos
Iakovos

Reputation: 1982

Try device.getName().equals("HTC") instead of device.equals("HTC").

At the moment your code is comparing an object of type BluetoothDevice to a string. Therefore, even if the device is available, you will not get a match, so the line device.createBond(); will never be reached.

Upvotes: 1

Related Questions