Android Bluetooth App Wont Run Due To Null Pointer Error
Solution 1:
It looks like the problem is from line 59: if (!mBluetoothAdapter.isEnabled()) {
Note: The error message says line 57, but in my text editor it says 59.
A few lines above, you check whether the object mBluetoothAdapter
was successfully created by checking if it's == null
. But after that, you call its method: .isEnabled()
. I think the problem is that mBluetoothAdapter
is becoming null
and therefore throws a NullPointerException when you try to access one of its methods.
If I understand correctly, I think the solution would be something like this:
// check if bluetooth is availableif(mBluetoothAdapter == null){
mBluetoothStatus.setText("Bluetooth is not available");
}
else {
mBluetoothStatus.setText("Bluetooth is available");
//if Bluetooth isnt enabled, enable itif (!mBluetoothAdapter.isEnabled()) {
IntentenableBtIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
This would keep the enabling code away from a mBluetoothAdapter
with a value of null
.
Alternativly, you could use return
to exit the method if BlueTooth isn't available.
// check if bluetooth is availableif(mBluetoothAdapter == null){
mBluetoothStatus.setText("Bluetooth is not available");
return;
}
else {
mBluetoothStatus.setText("Bluetooth is available");
}
//if Bluetooth isnt enabled, enable itif (!mBluetoothAdapter.isEnabled()) {
IntentenableBtIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
This would do the same in a little bit of a cleaner way.
I think the next step for you is to find out why BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
is returning null
instead of the object you want. I don't think the answer to that is in your MainActivity
method. The device isn't finding a default adapter and that could be the result of numerous problems.
Post a Comment for "Android Bluetooth App Wont Run Due To Null Pointer Error"