Bluetooth Connectivity Crashes when launched

kiwilifter picture kiwilifter · Jun 1, 2016 · Viewed 7.2k times · Source

When my app is launched every other feature works fine, but when tapping on the bluetooth button to turn on bluetooth, the app crashes and says that it has stopped. Sorry to be a pain and paste the entire bluetooth code. Its my first time using bluetooth and being new at android dev I'm not quite sure where i've gone wrong.. Any help is much appreciated.

Thank You

public class BluetoothActivity extends Activity {

private static final String TAG = "BluetoothActivity";
private static final int BLUETOOTH_REQUEST = 0;
private static final int SELECT_SERVER = 1;
public static final int DATA_RECEIVED = 3;
public static final int SOCKET_CONNECTED = 4;

public static final UUID APP_UUID = UUID
        .fromString("ad7b8520-f5fa-11e4-b939-0800200c9a66");
private Button on;
private Button off;
private Button server;
private Button client;
private TextView tv = null;

private BluetoothAdapter b_adapter = null;
private ConnectionThread bluetoothConnect = null;
private String data;
private boolean mServerMode;

private TextView text;
private ListView pairedList;
private Set<BluetoothDevice> pairedDevices;
private ArrayAdapter<String> BTArrayAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    b_adapter = BluetoothAdapter.getDefaultAdapter();
    if (b_adapter == null) {
        Log.i(TAG, "Bluetooth not supported");
        finish();
    }

    setContentView(R.layout.activity_bluetooth);
    tv = (TextView) findViewById(R.id.textView1);
    server = (Button) findViewById(R.id.server);
    server.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            startAsServer();
            mServerMode = true;
        }
    });

    client = (Button) findViewById(R.id.client);
    client.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            selectServer();
        }
    });

    if (!b_adapter.isEnabled()) {
        Intent enableBluetoothIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBluetoothIntent, BLUETOOTH_REQUEST);
    } else {
        setButtonsEnabled(true);
    }

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == BLUETOOTH_REQUEST && resultCode == RESULT_OK) {
        setButtonsEnabled(true);
    } else if (requestCode == SELECT_SERVER && resultCode == RESULT_OK) {
        BluetoothDevice device = data.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        connectToBluetoothServer(device.getAddress());
    }
}

private void startAsServer() {
    setButtonsEnabled(false);
    new AcceptThread(mHandler).start();
}

private void selectServer() {
    setButtonsEnabled(false);
    Set<BluetoothDevice> pairedDevices = b_adapter.getBondedDevices();
    ArrayList<String> pairedDeviceString = new ArrayList<String>();
    if (pairedDevices.size() > 0) {
        for (BluetoothDevice device : pairedDevices) {
            pairedDeviceString.add(device.getName() + "\n"
                    + device.getAddress());
        }
    }

Here is also the Bluetooth thread

public class ConnectThread extends Thread {
private BluetoothSocket BTsocket;
private final BluetoothDevice mDevice;
private final BluetoothAdapter b_adapter = BluetoothAdapter.getDefaultAdapter();
private final Handler mHandler;

public ConnectThread(String deviceID, Handler handler) {
    mDevice = b_adapter.getRemoteDevice(deviceID);
    mHandler = handler;
    try {
        BTsocket = mDevice.createRfcommSocketToServiceRecord(BluetoothActivity.APP_UUID);
    } catch (IOException e){
        e.printStackTrace();
    }
}
public void run() {
    b_adapter.cancelDiscovery();
    try {
        BTsocket.connect();
        manageConnectedSocket();
    } catch (IOException connectException) {    
        try {
            BTsocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

private void manageConnectedSocket() {
    ConnectionThread conn = new ConnectionThread(BTsocket, mHandler);
    mHandler.obtainMessage(BluetoothActivity.SOCKET_CONNECTED, conn).sendToTarget();
    conn.start();
}
public void cancel() {
    try {
        BTsocket.close();
    }catch(IOException e){

    }
}

}

For those wanting to view the logcat. Here it is below.

.BluetoothActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
  at android.app.ActivityThread.-wrap11(ActivityThread.java)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
  at android.os.Handler.dispatchMessage(Handler.java:102)
  at android.os.Looper.loop(Looper.java:148)
  at android.app.ActivityThread.main(ActivityThread.java:5417)
  at java.lang.reflect.Method.invoke(Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.isEnabled()' on a null object reference
  at com.kenpar.dmsassign2.BluetoothActivity.onCreate(BluetoothActivity.java:80)
  at android.app.Activity.performCreate(Activity.java:6237)
  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
  at android.app.ActivityThread.-wrap11(ActivityThread.java) 
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
  at android.os.Handler.dispatchMessage(Handler.java:102) 
  at android.os.Looper.loop(Looper.java:148) 
  at android.app.ActivityThread.main(ActivityThread.java:5417) 
  at java.lang.reflect.Method.invoke(Native Method) 
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Answer

Rehan picture Rehan · Jun 1, 2016

It is because your BluetoothAdapter might not be initialized properly. Check your LogCat, you should see Bluetooth not supported message in info tag. Now to avoid NullPointerException in your Activity, change your code to this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    b_adapter = BluetoothAdapter.getDefaultAdapter();
    if (b_adapter == null) {
        Log.i(TAG, "Bluetooth not supported");
        // Show proper message here
        finish();
    } else {
        setContentView(R.layout.activity_bluetooth);
        tv = (TextView) findViewById(R.id.textView1);
        server = (Button) findViewById(R.id.server);
        server.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startAsServer();
                mServerMode = true;
            }
        });

        client = (Button) findViewById(R.id.client);
        client.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                selectServer();
            }
        });

        if (!b_adapter.isEnabled()) {
            Intent enableBluetoothIntent = new Intent(
                BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetoothIntent, BLUETOOTH_REQUEST);
        } else {
            setButtonsEnabled(true);
        }
    }
}

The reason is: if your b_adapter is null, it should not execute the lines using it. To make it clear finish does not skip the lines next to it. So you have to do it by yourself.