Android bluetooth crashing application

Having some trouble using device.getName(). It's for some reason causing my application to crash.

What I'm doing is displaying an adapter (holding bluetooth names) in a dialogue box. When I run the application and adding device.getAdress() instead of - .getName() the application works fine, but when doing it with .getName() it crashes.

mBluetoothAdapter.startDiscovery();
receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            toothadapter.add(device.getName());
            toothadapter.notifyDataSetChanged();
        }
    }
};
AlertDialog.Builder builder = new AlertDialog.Builder(bluetooth.this);
builder.setTitle("Nearby Devices:");
builder.setAdapter(toothadapter, new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int item) {

    }
});
AlertDialog alert = builder.create();
alert.show();

IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);

Really need some help as to why this is happening. The code above this, is all included in onCreate() within a buttonListener.

Upvotes: 2

Views: 793

Answers (1)

Onik
Onik

Reputation: 19959

Really need some help as to why this is happening.

It is hardly possible to say for sure what causes the app crash without seeing the stacktrace.

However note that BluetoothDevice.getName() returns null if "there was a problem". And we know (from the Toast notifications you get) that the method returns nulls in the app. These nulls may or may not be the reason of the crash.

In addition, the place where null device name cannot cause NPE is ArrayAdapter. When you call new ArrayAdapter<String>(Context, int) the following constructor is invoked:

public ArrayAdapter(Context context, int resource) {
    init(context, resource, 0, new ArrayList<T>());
}

Data structure used to store your data is ArrayList whose add()'s method implementation allows adding null as opposed to the List<>'s add() method declaration.

Upvotes: 1

Related Questions