skip to Main Content

When trying to make a popup dialog with paired bluetooth devices in a spinner, my app crashes upon opening. See this code for the xml layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">
    
    <Spinner
        android:id="@+id/spinner_devices"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/bConnectBtn"
        android:text="CONNECT"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

In the code below here, I call a function that checks for bonded devices and then puts it in the spinner:

private fun onBluetoothEnabled() {
    val bondedDevices = bluetoothAdapter?.bondedDevices
    if (bondedDevices != null) {
        val bondedAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, bondedDevices.map { it.name })
        bondedAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner_devices.adapter = bondedAdapter

        bConnectBtn.setOnClickListener {
            val device = bondedDevices.toList()[spinner_devices.selectedItemPosition]
            setupClient(device)
        }
    }
}

Here I show the dialog:

val bluetoothView = layoutInflater.inflate(R.layout.bluetoothdialog, null)
val bluetoothDialog = AlertDialog.Builder(this@MainActivity)

bluetoothDialog.setTitle("Paired Devices")
bluetoothDialog.setView(bluetoothView)
bluetoothDialog.setCancelable(false)
bluetoothDialog.setNeutralButton("TEMP CLOSE") { _, _ -> }

bluetoothDialog.show()

Some extra details about this, this works just fine when the spinner is in the main activity xml, but when I put the spinner in a popup dialog xml file, it crashes upon start. When I add ? or !! to spinner_devices?.adapter it works but doesn’t fill the spinner with the bonded devices which makes sense because it allows null now.

When I debug my code, I can see that the bondedApapter gets filled with paired bluetooth devices, but when it gets to the spinner_devices.adapter it is null. Any guesses on what I am doing wrong?

2

Answers


  1. Chosen as BEST ANSWER

    For those wondering. I was able to fix it and made it a bit more usefull by being able to click on a bluetooth device and make it connect. See code below for full code:

    private fun showPairedDevicesPopup() {
        val bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        val pairedDevices: Set<BluetoothDevice> = bluetoothAdapter.bondedDevices
    
        // Create a list of device names
        val deviceNames = ArrayList<String>()
        pairedDevices.forEach { deviceNames.add(it.name) }
    
        // Create an array adapter to display the list of device names
        val adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, deviceNames)
    
        // Build the alert dialog
        val builder = AlertDialog.Builder(this)
        builder.setTitle("Paired Devices")
        builder.setCancelable(false)
        builder.setAdapter(adapter) { _, which ->
            // Get the selected device
            val selectedDevice = pairedDevices.elementAt(which)
    
            // Attempt to connect to the selected device
            val socket: BluetoothSocket?
            try {
                socket = selectedDevice.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"))
                socket.connect()
            } catch (e: IOException) {
                // Failed to connect to the device
                e.printStackTrace()
            }
        }
        builder.setNegativeButton("Cancel") { dialog, _ ->
            dialog.dismiss()
        }
    
        // Show the alert dialog
        val dialog = builder.create()
    
        dialog.show()
    }
    

  2. There is some object initialization when you tries to bind adapter from AlertDialog. Checkout the below code that is working fine.

    val bluetoothView = layoutInflater.inflate(R.layout.bluetoothdialog, null)
    val bluetoothDialog = AlertDialog.Builder(this@MainActivity)
    bluetoothDialog.setTitle("Paired Devices")
    bluetoothDialog.setView(bluetoothView)
    bluetoothDialog.setCancelable(false)
    bluetoothDialog.setNeutralButton("TEMP CLOSE") { _, _ ->}
    bluetoothDialog.show()
    

    **//get views from inflated layout

    val spinnerDevices = bluetoothView.findViewById(R.id.spinner_devices)

    val bConnectBtn = bluetoothView.findViewById(R.id.bConnectBtn)**

     //bind adapter
    val bondedAdapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, bondedDevices.map { it.name })
                   bondedAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    spinnerDevices.adapter = bondedAdapter
    
    bConnectBtn.setOnClickListener {
    val device = bondedDevices.toList()[spinnerDevices.selectedItemPosition]
    Toast.makeText(this@MainActivity,"Connection to:${device.name}",Toast.LENGTH_SHORT).show()
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search