I am trying to save the radio button user response in Firestore under the UID. I have two choices yes
and no
to the question. It only works one time that the user selects a choice with a button pressed but if the user wants to change the answer it does not update (replace the old response).
I am wondering if anyone can help so that the selected response can be updated.
buttonfor.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String yes = yesButton.getText().toString();
String no = yesButton.getText().toString();
Map<String, Object> user = new HashMap<>();
if (radioGroup.getCheckedRadioButtonId() == R.id.question_a1) {
user.put("I am wiling to participate", yes);
} else if (radioGroup.getCheckedRadioButtonId() == R.id.question_a2){
user.put("I am wiling to participate", no);
}
userID = fAuth.getCurrentUser().getUid();
fStore.collection("users").document(userID).set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(question.this, "User Response Saved", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(question.this, "Error!", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
}
});
In addition, I also tried but the response does not update in Firestore
if (yesButton.isChecked()){
user.put("I am wiling to participate", yes);
} else if (noButton.isChecked()){
user.put("I am wiling to participate", no);
}
And with update
instead of set
also did not work…
fStore.collection("users").document(userID).update(user).addOnSuccessListener(new OnSuccessListener<Void>()
2
Answers
Sorry I am not able to comment yet!
If your question is not solved yet, please may you provide more code because per my check on the code snippet you provided I cannot detect where the error is coming from.
To solve this, first, you have to create a layout that contains two radio buttons:
Then inside your activity, you have to find them by id and attach a real-time listener. Assuming that your Firestore schema looks like this:
Here is the code:
Define them as members of the class (global variables):
Add inside onCreate:
Here is to code for attaching a click listener on each radio button:
And here is the method which is responsible for the update: