I have a problem regarding my Bluetooth app. When I enable Bluetooth before starting up the app everything works alright. But when I don't, my app will ask permission to enable Bluetooth via the turnOn method. But when I press my onScan button I get a error stating:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.startScan(android.bluetooth.le.ScanCallback)' on a null object reference
here is my onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set layout
setContentView(R.layout.activity_main);
//Bluetooth
// BluetoothManager
final BluetoothManager BTManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
BTAdapter = BTManager.getAdapter();
// BluetoothLescanner
BTScanner = BTAdapter.getBluetoothLeScanner();
//Turn on BT
turnOn();
//Ask permission for location.
requestPermission();
}
My ques is that, BTScanner is made before the turnOn method is called, making the BTScanner a null object.
Any help regarding this problem would be greatly.
Kind regards,
Binsento
Try this (taken from one of my projects):
Class variable:
private BluetoothAdapter mBtAdapter = null;
Inside onCreate
:
final BluetoothManager btManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBtAdapter = btManager.getAdapter();
checkBt(); // called at the end of onCreate
The checkBt()
method:
private void checkBt() {
if (mBtAdapter == null || !mBtAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
Then from there when the "Scan" button is clicked:
public void onScanButton(){
if (mBtAdapter.isEnabled()){
scanLeDevice(true);
}
}
Then scanLeDevice
calls mBtAdapter.startLeScan(mLeScanCallback);
NOTE: Some of this is now deprecated but can be updated to comply with the new API. I have not taken the time to do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With