I am trying to store ‘yes’ if a person clicks on the radio button with id – "negotiable" else stores ‘no’ if clicked on id ‘nonNegotiable’ or when nothing is selected.
Kotlin Function
private fun addProduct(): HashMap<String, String?> {
val sProductId = UUID.randomUUID().toString()
val sItemName = findViewById<EditText>(R.id.itemName).text.toString()
val sItemCategory = selectedValue
val sDescription = findViewById<EditText>(R.id.description).text.toString()
val sPrice = findViewById<EditText>(R.id.price).text.toString()
val radioGroup = findViewById<RadioGroup>(R.id.radioGroup)
var sNegotiable: String? = null
radioGroup.setOnCheckedChangeListener { group, checkedId ->
sNegotiable = if (checkedId == R.id.negotiable) {
"yes"
} else {
"no"
}
}
return hashMapOf(
"productId" to sProductId,
"itemName" to sItemName,
"itemCategory" to sItemCategory,
"description" to sDescription,
"price" to sPrice,
"negotiable" to sNegotiable
)
Xml code –
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="210dp"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
app:layout_constraintBottom_toTopOf="@+id/addProduct"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent">
<RadioButton
android:id="@+id/negotiable"
android:layout_width="match_parent"
android:layout_height="48dp"
android:text="@string/negotiable" />
<RadioButton
android:id="@+id/nonNegotiable"
android:layout_width="match_parent"
android:layout_height="48dp"
android:text="@string/non_negotiable" />
</RadioGroup>
I am storing this in firebase firestore and it is storing null in negotiable.
2
Answers
The problem that you’re facing here is due to the fact that your function is probably returning waaaay before the click listener is registered, and calls you back.
Instead, you should make an effort to update whatever it is that you’re trying to update with the
return hasMapOf(...)
call, probably in an async way as to avoid any complications.Try to refactor your code to something like this instead:
This way, you’ll get notified every time a radio button is clicked, and therefore the data changes, and you’ll be able to act accordingly every time that happens. Of course, you’ll want to unregister the callback once you’re done, as to avoid having any memory leaks, or any other kind of unforeseen issue!
setOnCheckedChangeListener
is an async function, code inside the listener is not executed immediately, so when you return theHashMap
,sNegotiable
might still benull
because the listener may not have been triggered yet.One way to handle this is by using a callback to update your
HashMap
after theRadioGroup
selection changes. Here’s an example:By using a callback, you ensure that the
HashMap
is updated after theRadioGroup
selection changes and before you return it. Adjust this example according to your specific use case and how you interact with Firebase Firestore.