1

Доброго времени суток.

Приложение вылетает с NullPointerException при попытке подключения к Bluetooth устройству (HC-05). Сопряжение с ним проходит нормально, но вот дальнейшее соединение (создание сокета и тд.) не выходит - метод startClient(device) в onItemClick(). Toast с содержимым объекта device нормально выводит его имя и адрес, но вот startClient() ругается (полный лог ниже):

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.bttest.BluetoothConnectionService.startClient(android.bluetooth.BluetoothDevice)' on a null object reference

Скорее всего я тупо напортачил в классе BluetoothConnectionSrvice, т.к. не имею должного опыта.

Заранее благодарю за помощь

Код MainActivity:

public class MainActivity extends AppCompatActivity implements
        CompoundButton.OnCheckedChangeListener,
        AdapterView.OnItemClickListener,
        View.OnClickListener {

private static final String TAG = "BTCS";
private static final int REQUEST_ENABLE_BT      = 1;  // Включение BT
private static final int REQUEST_CODE_LOCATION  = 4;  //Данные о местоположении

private Switch btSwitch;                    // Switch
private LinearLayout foundDeviceListFrame;  // Фрейм с найденными устройствами
private LinearLayout bondedDeviceListFrame; // Фрейм с сопряженными устройствами
private ListView bondedDeviceList;          // Список найденных устройств
private ListView foundDeviceList;           // Список сопряженных устройств
private Button btnStartSearch;              // Кнопка "Поиск"
private ProgressBar pbSearchProgress;       // Search Progress Bar

private BluetoothAdapter bluetoothAdapter;                     // Bluetooth адаптер смартфона
private BondedListAdapter bondedListAdapter;                   // Адаптер для сопряженных устройств
private FoundListAdapter foundListAdapter;                     // Адаптер для найденных устройств
private ArrayList<BluetoothDevice> foundBluetoothDevices;      // Массив найденных устройств
private ArrayList<BluetoothDevice> bondedBluetoothDevices;     // Массив сопряженных устройств
private MacAddressMask checkMacAddress;                        // Проверка МАС адресов

private TextView myDeviceInfo;        // Инфо об устройстве пользователя
private String myDeviceName;          // Имя устройства пользователя
private String myDeviceAddress;       // Адрес устройства пользователя

BluetoothConnectionService mBluetoothConnection;
private static final UUID USER_UUID = UUID.fromString("f1190e86-3bb8-433e-8de7-ef29d4cb252a");

private RelativeLayout ledControlFrame;  // Фрейм с управлением устройством
private Button ledControlBtnDisconnect;  // Кнопка Disconnect
private Switch ledControlSwitch;         // Включение/Отключение светодиода
private TextView ledControlTV;           // Текстовое поле для приема данных

@SuppressLint("HardwareIds")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btSwitch              = findViewById(R.id.switch_bt_on_off);      // Switch для вкл/выкл BT
    foundDeviceListFrame  = findViewById(R.id.found_device_list);     // Фрейм с найденными устройствами
    bondedDeviceListFrame = findViewById(R.id.bonded_device_list);    // Фрейм с сопряженными устройствами
    bondedDeviceList      = findViewById(R.id.lv_bt_devices_bonded);  // Список сопряженных устройств
    foundDeviceList       = findViewById(R.id.lv_bt_devices_found);   // Список найденных устройств
    btnStartSearch        = findViewById(R.id.btn_startSearch);       // Кнопка "Поиск"
    pbSearchProgress      = findViewById(R.id.pb_search_progress);    // Search Progress Bar

    myDeviceInfo = findViewById(R.id.tv_my_device_info);              // Инфо о моем устройстве

    ledControlFrame         = findViewById(R.id.led_control_frame);
    ledControlBtnDisconnect = findViewById(R.id.led_control_btn_disconnect);
    ledControlSwitch        = findViewById(R.id.led_control_switch);
    ledControlTV            = findViewById(R.id.led_control_tv);


    btSwitch.setOnCheckedChangeListener(this);       // Включение BT
    bondedDeviceList.setOnItemClickListener(this);   // Ячейка сопряженных устройств
    foundDeviceList.setOnItemClickListener(this);    // Ячейка найденных устройств
    btnStartSearch.setOnClickListener(this);         // Поиск

    ledControlBtnDisconnect.setOnClickListener(this);  // Отключение
    ledControlSwitch.setOnCheckedChangeListener(this); // Включение светодиода

    foundBluetoothDevices = new ArrayList<>();
    bondedBluetoothDevices = new ArrayList<>();
    checkMacAddress = new MacAddressMask();

    IntentFilter filter = new IntentFilter();
    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    filter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
    filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
    filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
    filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    registerReceiver(mReceiver, filter);

    IntentFilter searchFilter = new IntentFilter();
    searchFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    searchFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    searchFilter.addAction(BluetoothDevice.ACTION_FOUND);
    registerReceiver(searchReciever, searchFilter);

    IntentFilter btcsFilter = new IntentFilter();
    btcsFilter.addAction(BluetoothConnectionService.ACTION_SOCKET_NOT_CONNECTED);
    LocalBroadcastManager.getInstance(this).registerReceiver(BTCSReceiver, btcsFilter);

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
     if (bluetoothAdapter == null) {
         Toast.makeText(this, "Bluetooth не поддерживается устройством", Toast.LENGTH_SHORT).show();
         Log.d(TAG, "Bluetooth not supported");
         finish();
     }

     if (!bluetoothAdapter.isEnabled()) {
         Log.d(TAG, "Bluetooth is NOT enabled");
         Intent btOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
         startActivityForResult(btOn, REQUEST_ENABLE_BT);
     }

     if (bluetoothAdapter.isEnabled()) {
         Log.d(TAG, "Bluetooth is enabled");
         getUserDeviceInfo();
         showDeviceList();
         btSwitch.setChecked(true);
         setBondedDeviceList();
     }

    foundBluetoothDevices.clear();                                                  // Очистка списка найденных устройств
    foundListAdapter = new FoundListAdapter(this, foundBluetoothDevices);   // Адаптер для найденных устройств
    foundDeviceList.setAdapter(foundListAdapter);                                   // Привязка адаптера

}

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(mReceiver);
    unregisterReceiver(searchReciever);
    unregisterReceiver(BTCSReceiver);
}

@Override
public void onClick(View v) {
    if (v.equals(btnStartSearch)){
        startSearch();
    }
    else if (v.equals(ledControlBtnDisconnect)) {
        // TODO отключение от устройства;
    }
}

private void startSearch() {
    if (bluetoothAdapter.isDiscovering()) {
        bluetoothAdapter.cancelDiscovery();
        Log.d(TAG, "Discovery cancelled");
    } else {
        accessLocationPermission();
        bluetoothAdapter.startDiscovery();
        Log.d(TAG, "Discovery started");
        foundBluetoothDevices.clear();
        foundListAdapter.notifyDataSetChanged();
    }
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
    bluetoothAdapter.cancelDiscovery();

    if (parent.equals(foundDeviceList)) {
        BluetoothDevice device = foundBluetoothDevices.get(position);
        if (device != null) {
        device.createBond();
            Log.d(TAG, "Bond created: " + device.getName() + " " + device.getAddress());
        }
    }
    if (parent.equals(bondedDeviceList)) {
        BluetoothDevice device = bondedBluetoothDevices.get(position);
        if (device != null) {
            Toast.makeText(this, device.getAddress() + "" + device.getName(), Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Line №197");
            mBluetoothConnection.startClient(device);
        }
    }
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if (buttonView.equals(btSwitch)) {
        enableBt(isChecked);
        if (!isChecked) {
            hideDeviceList();
        }
    }
    else if (buttonView.equals(ledControlSwitch)) {
        // TODO включение светодтода
        mBluetoothConnection.write(isChecked);
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_ENABLE_BT) {
        if (resultCode == RESULT_OK && bluetoothAdapter.isEnabled()) {
            showDeviceList();
        }

        else if (resultCode == RESULT_CANCELED) {
            btSwitch.setChecked(false);
        }
    }
}

private void showDeviceList() {
    foundDeviceListFrame.setVisibility(View.VISIBLE);
    bondedDeviceListFrame.setVisibility(View.VISIBLE);
    ledControlFrame.setVisibility(View.GONE);
}
private void hideDeviceList() {
    foundDeviceListFrame.setVisibility(View.GONE);
    bondedDeviceListFrame.setVisibility(View.GONE);
    ledControlFrame.setVisibility(View.GONE);
}

private void showLedControlFrame() {
    ledControlFrame.setVisibility(View.VISIBLE);
    foundDeviceListFrame.setVisibility(View.GONE);
    bondedDeviceListFrame.setVisibility(View.GONE);
}

private void getUserDeviceInfo() {
    myDeviceName    = bluetoothAdapter.getName();
    myDeviceAddress = bluetoothAdapter.getAddress();
    myDeviceInfo.setText(myDeviceName + "\n" + myDeviceAddress);
}

private void enableBt(boolean flag) {
    if (flag) {
        Intent btOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(btOn, REQUEST_ENABLE_BT);
    }
    else {
        bluetoothAdapter.disable();
    }
}

 private ArrayList<BluetoothDevice> getBondedBtDevices() {
    Set<BluetoothDevice> deviceSet = bluetoothAdapter.getBondedDevices();
    ArrayList<BluetoothDevice> tmpArrayList = new ArrayList<>();
    if (deviceSet.size() > 0) {
        for (BluetoothDevice device: deviceSet) {
            if (checkMacAddress.macAddressMask(device.getAddress())) {
                tmpArrayList.add(device);
                Log.d(TAG, "Got bonded device: " + device.getName() + " " + device.getAddress());
            }
        }
    }
    return tmpArrayList;
 }

 private void setBondedDeviceList() {
    bondedBluetoothDevices.clear();
    showDeviceList();
    bondedBluetoothDevices = getBondedBtDevices();
    bondedListAdapter = new BondedListAdapter(this, bondedBluetoothDevices);  // Адаптер для сопряженных устройств
    bondedDeviceList.setAdapter(bondedListAdapter);                                   // Привязка адаптера
 }

private final BroadcastReceiver searchReciever = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
         String action = intent.getAction();

         switch (action) {
            case BluetoothAdapter.ACTION_DISCOVERY_STARTED:
                btnStartSearch.setText("Остановить поиск");
                pbSearchProgress.setVisibility(View.VISIBLE);
                showDeviceList();
                Log.d("searchReceiver", "BluetoothAdapter.ACTION_DISCOVERY_STARTED");
                break;

            case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
                 btnStartSearch.setText("Начать поиск");
                 pbSearchProgress.setVisibility(View.INVISIBLE);
                Log.d("searchReceiver", "BluetoothAdapter.ACTION_DISCOVERY_FINISHED");
            break;

            case BluetoothDevice.ACTION_FOUND:
                 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                 if (device != null && !foundBluetoothDevices.contains(device) && device.getBondState() == BluetoothDevice.BOND_NONE && checkMacAddress.macAddressMask(device.getAddress()) == true) {
                         foundBluetoothDevices.add(device);
                         foundListAdapter.notifyDataSetChanged();
                     Log.d("searchReceiver", "BluetoothDevice.ACTION_FOUND");
                 }
            break;
        }
    }
};

/**
 * Слушатель состояния Bluetooth
 **/

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                final String action = intent.getAction();

                if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                    final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                            BluetoothAdapter.ERROR);
                    switch (state) {
                        case BluetoothAdapter.STATE_OFF:
                            btSwitch.setChecked(false);
                            Log.d("mReceiver", "BluetoothAdapter.STATE_OF");
                            break;
                        case BluetoothAdapter.STATE_TURNING_OFF:
                            // Turning Bluetooth off...
                            Log.d("mReceiver", "BluetoothAdapter.STATE_TURNING_OFF");
                            break;
                        case BluetoothAdapter.STATE_ON:
                            btSwitch.setChecked(true);
                            setBondedDeviceList();
                            showDeviceList();
                            getUserDeviceInfo();
                            Log.d("mReceiver", "BluetoothAdapter.STATE_ON");
                            break;
                        case BluetoothAdapter.STATE_TURNING_ON:
                            Log.d("mReceiver", "BluetoothAdapter.STATE_TURNING_ON");
                            break;
                    }
                }

                if (action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                    setBondedDeviceList();
                    startSearch();
                    bondedListAdapter.notifyDataSetChanged();
                    foundListAdapter.notifyDataSetChanged();
                }
            }
        };

private BroadcastReceiver BTCSReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothConnectionService.ACTION_SOCKET_NOT_CONNECTED)) {
            Toast.makeText(getApplicationContext(), "Типа соединяюсь с устройством", Toast.LENGTH_SHORT).show();
            Log.e(TAG, "connectThread: run: Could not connect");
        }
        if (action.equals(BluetoothConnectionService.ACTION_SUCCESS)) {
            Log.d(TAG, "ACTION_SUCCESS");
            showLedControlFrame();
        }
    }
};

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    switch (requestCode) {
        case REQUEST_CODE_LOCATION:

            if (grantResults.length > 0) {
                for (int gr: grantResults) {
                    if (gr != PackageManager.PERMISSION_GRANTED) {
                        return;
                    }
                }
            }
            break;
        default:
            return;
    }
}

/**
 *Запрос на разрешение получения данных о местоположении (6.0)
 **/
private void accessLocationPermission() {
    int accessCoarseLocation = this.checkSelfPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION);
    int accessFineLocation   = this.checkSelfPermission(android.Manifest.permission.ACCESS_FINE_LOCATION);

    List<String> listRequestPermission = new ArrayList<String>();

    if (accessCoarseLocation != PackageManager.PERMISSION_GRANTED) {
        listRequestPermission.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    if (accessFineLocation != PackageManager.PERMISSION_GRANTED) {
        listRequestPermission.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
    }

    if (!listRequestPermission.isEmpty()) {
        String[] strRequestPermission = listRequestPermission.toArray(new String[listRequestPermission.size()]);
        this.requestPermissions(strRequestPermission, REQUEST_CODE_LOCATION);
    }
}
}

Код из класса BluetoothConnectionService:

public class BluetoothConnectionService {

public static final String ACTION_SOCKET_NOT_CONNECTED = "Socket connection failed";
public static final String ACTION_SUCCESS              = "Device Connected";

private static final String TAG = "BTCS";

private static final UUID MY_UUID = UUID.fromString("f1190e86-3bb8-433e-8de7-ef29d4cb252a");
private UUID deviceUUID;
Context mContext;

private final BluetoothAdapter mBluetoothAdapter;
private ConnectThread connectThread;
private ConnectedThread connectedThread;

public BluetoothConnectionService(Context context) {
    mContext = context;
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}

public class ConnectThread extends Thread {
    private BluetoothSocket bluetoothSocket = null;
    private boolean success = false;

    public ConnectThread(BluetoothDevice device) {
        //device = device;
        //deviceUUID = uuid;
        try {
            Method method = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
            bluetoothSocket = (BluetoothSocket) method.invoke(device, 1);

//  Другой способ              Log.d(TAG, "ConnectThread: Trying to create RfcommSocket using UUID: " + USER_UUID);
//  (тоже ошибка)              bluetoothSocket = device.createRfcommSocketToServiceRecord(deviceUUID);
            }
            catch (Exception e) {
                Log.e(TAG, "ConnectThread: Could not create RfcommSocket " + e.getMessage());
            }
            mBluetoothAdapter.cancelDiscovery();
    }

    @Override
    public void run() {
        try {
            bluetoothSocket.connect();
            Log.d(TAG, "run: ConnectThread connected. ");
        }
        catch (IOException e) {
            Log.e(TAG, "run: Could not connect");
            Intent intent = new Intent(ACTION_SOCKET_NOT_CONNECTED);
            intent.putExtra("Debug", "ConnectThread: run: Could not connect");
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
            cancel();
        }

        if (success) {
            connectedThread = new ConnectedThread(bluetoothSocket);
            connectedThread.start();
            Intent intent = new Intent(ACTION_SUCCESS);
            intent.putExtra("success", "Device connected");
            LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
        }
    }

    public boolean isConnect() {
        return bluetoothSocket.isConnected();
    }

    public void cancel() {
        try {
            Log.d(TAG, "cancel: Closing Client Socket. ");
            bluetoothSocket.close();
        }
        catch (IOException e) {
            Log.e(TAG, "cancel: close() of bluetoothSocket in ConnectThread failed. " + e.getMessage());
        }
    }
}

private class ConnectedThread extends Thread {
    private final InputStream inputStream;
    private final OutputStream outputStream;

    public ConnectedThread(BluetoothSocket bluetoothSocket) {
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            inputStream = bluetoothSocket.getInputStream();
            outputStream = bluetoothSocket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "Could not get streams " + e.getMessage());
        }

        this.inputStream = inputStream;
        this.outputStream = outputStream;
    }

    public void write(String command) {
        byte[] bytes = command.getBytes();
        Log.d(TAG, "write: Writing to outputStream: " + bytes);
        if (outputStream != null) {
            try {
                outputStream.write(bytes);
                outputStream.flush();
            }
            catch (IOException e) {
                Log.e(TAG, "write: Error writing to output stream. " + e.getMessage());
            }
        }
    }

    public void cancel() {
        try {
            inputStream.close();
            outputStream.close();
        }
        catch (IOException e) {
            Log.e(TAG, "run: close: Could not close streams");
        }
    }
}

public void write(boolean state) {
    if (connectedThread != null && connectThread.isConnect()) {
        String command = "";
        if (state) {
            command = "on#";
        }
        if (!state) {
            command = "off#";
        }
        connectedThread.write(command);
    }
}

public void startClient(BluetoothDevice device) {
    Log.d(TAG, "startClient: Started. ");

    connectThread = new ConnectThread(device);
    connectThread.start();
}
}

Логи:

2020-08-13 12:30:53.085 8333-8333/com.example.bttest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bttest, PID: 8333
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.bttest.BluetoothConnectionService.startClient(android.bluetooth.BluetoothDevice)' on a null object reference
    at com.example.bttest.MainActivity.onItemClick(MainActivity.java:197)
    at android.widget.AdapterView.performItemClick(AdapterView.java:374)
    at android.widget.AbsListView.performItemClick(AbsListView.java:1736)
    at android.widget.AbsListView$PerformClick.run(AbsListView.java:4207)
    at android.widget.AbsListView$7.run(AbsListView.java:6692)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:237)
    at android.app.ActivityThread.main(ActivityThread.java:7814)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)
2
  • А где вы инициализируете mBluetoothConnection? 13 авг 2020 в 8:08
  • Так и есть, благодарю. 13 авг 2020 в 9:01

1 ответ 1

0

Ну собственно ваша проблема в том, что вы нигде не ининциализируете ваш объект BluetoothConnectionService. А значит он null, о чем вам и говорит ошибка.

BluetoothConnectionService bluetoothConnectionService = new BluetoothConnectionService(context);

Должно решить вашу проблему

4
  • Боже, даже стыдно, на такой простой вещи сел. Спасибо. Теперь вроде как-то еще работает, но не до конца, но это уже совсем другая проблема. Сделал инициализацию сразу перед startClient()- это правильно? Или лучше ее проводить непосредственно в onCreate()? 13 авг 2020 в 9:01
  • 1
    Ну я думаю, что инициализировать нужно непосредственно перед первым местом вызова. Допустим вы можете в какой-то момент даже не дойти до использования вашего объекта, зачем тогда вы его будет создавать заранее если он ни разу не используется? 13 авг 2020 в 9:10
  • Так и думал, поэтому и вызываю перед созданием сокета. Спасибо. Теперь еще один вопрос: в чем отличие между созданием сокета через рефлексию (реализовано в ConnectThread) и между тем что ниже закомментировано. Я вижу разницу только в наличии/отсутствии UUID. Только вот создание через рефлексию работает, а напрямую нет. 13 авг 2020 в 9:27
  • UPD коммента выше. Реализовал с использованием UUID, хотя так и не допер зачем он нужен 13 авг 2020 в 13:20

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.