Ted Tedson
Ted Tedson

Reputation: 316

How to pass string array to AlertDialog builder.setItems()

I am using Alert Dialog builder in order to visualize the paired bluetooth devices. I want to pass a sstring array to the setItems() method in order to create the list with the devices. setItems() gets CharSequence[] and a listener. When i pass the string array it fails. How can i fix it? Here is the code:

public void showPairedDevices() {
    String[] pairedDevicesArray = new String[100];

    // Get a set of currently paired devices
    Set<BluetoothDevice> pairedDevicesSet = bluetoothAdapter
            .getBondedDevices();

    if (pairedDevicesSet.size() > 0) {
        int i = 0;
        for (BluetoothDevice device : pairedDevicesSet) {
            pairedDevicesArray[i] = device.getName();
            i++;
        }

        connectDialog = new AlertDialog.Builder(context);
        connectDialog.setTitle("Paired devices");
        connectDialog.setItems(pairedDevicesArray, connectDialogClickListener);
        connectDialog.show();

    } else {
        Toast.makeText(context, "No paired devices!", Toast.LENGTH_SHORT)
                .show();
    }
}

private OnClickListener connectDialogClickListener = new OnClickListener() {
    @Override
    public void onClick(DialogInterface connectDialog, int button) {
        connectDialog.dismiss();
    }
};

Upvotes: 0

Views: 2793

Answers (1)

Andrew Schuster
Andrew Schuster

Reputation: 3229

Your issue stems from the fact that you're starting with a String array that is too big. When you initialize an array of objects, every space is by default null. With that in mind, what you should know is that when you feed an array that is of length 100 to setItem(), it is going to check every index, and if it finds a null it will throw an error. Here is a proposed solution:

public void showPairedDevices() {
    // Get a set of currently paired devices
    Set<BluetoothDevice> pairedDevicesSet = bluetoothAdapter
            .getBondedDevices();

    if (pairedDevicesSet.size() > 0) {

        // This will set the size of the array to exactly how many you need
        String[] pairedDevicesArray = new String[pairdDevicesSet.size()];

        int i = 0;
        for (BluetoothDevice device : pairedDevicesSet) {
            pairedDevicesArray[i] = device.getName();
            i++;
        }

        // ...
}

Upvotes: 1

Related Questions