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
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:
There is some object initialization when you tries to bind adapter from
AlertDialog
. Checkout the below code that is working fine.**//get views from inflated layout
val spinnerDevices = bluetoothView.findViewById(R.id.spinner_devices)
val bConnectBtn = bluetoothView.findViewById(R.id.bConnectBtn)**
}