NullPointerException on BluetoothGatt.close() when the gatt object is not null

When I try to close my GATT connection, I do the following:

BluetoothGatt gatt;
...
private void disconnectDevice() {
    ...
    if (this.gatt != null) {
        this.gatt.disconnect();
        this.gatt.close();
        this.gatt = null;
    }
    ...
}

However, the app crashes with a NullPointerException in the this.gatt.close(); line (not in the disconnect() line) on my Samsung Galaxy S4 mini. When I remove the this.gatt.close(); line (but keep the disconnect() line), the problem disappears. On my Samsung Galaxy S5 and on my Vodafone Smart prime 6, I do not have that kind of problem.

However, the Android reference encourages me to call the close() function when I am done.

Here is the log message:

D/AndroidRuntime(26003): Shutting down VM
W/dalvikvm(26003): threadid=1: thread exiting with uncaught exception (group=0x41813da0)
E/AndroidRuntime(26003): FATAL EXCEPTION: main
E/AndroidRuntime(26003): Process: org.kolodez.MyApp, PID: 26003
E/AndroidRuntime(26003): java.lang.NullPointerException
E/AndroidRuntime(26003):    at org.kolodez.MyApp.ServiceMain.disconnectDevice(ServiceMain.java:575)
E/AndroidRuntime(26003):    at org.kolodez.MyApp.ServiceMain.access$1800(ServiceMain.java:34)
E/AndroidRuntime(26003):    at org.kolodez.MyApp.ServiceMain$MyBinder.disconnectDevice(ServiceMain.java:536)
E/AndroidRuntime(26003):    at org.kolodez.MyApp.ActivityMainLayoutMain.connectDisconnect(ActivityMainLayoutMain.java:377)
E/AndroidRuntime(26003):    at org.kolodez.MyApp.ActivityMainLayoutMain.access$1100(ActivityMainLayoutMain.java:36)
E/AndroidRuntime(26003):    at org.kolodez.MyApp.ActivityMainLayoutMain$ButtonListener.onClick(ActivityMainLayoutMain.java:527)
E/AndroidRuntime(26003):    at android.view.View.performClick(View.java:4881)
E/AndroidRuntime(26003):    at android.view.View$PerformClick.run(View.java:19592)
E/AndroidRuntime(26003):    at android.os.Handler.handleCallback(Handler.java:733)
E/AndroidRuntime(26003):    at android.os.Handler.dispatchMessage(Handler.java:95)
E/AndroidRuntime(26003):    at android.os.Looper.loop(Looper.java:146)
E/AndroidRuntime(26003):    at android.app.ActivityThread.main(ActivityThread.java:5756)
E/AndroidRuntime(26003):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(26003):    at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(26003):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
E/AndroidRuntime(26003):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
E/AndroidRuntime(26003):    at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager(  785):   Force finishing activity org.kolodez.MyApp/.ActivityMain

Source: Android Questions

LEAVE A COMMENT