I am trying to use addSnapshotListener to listen to the changes of radiobutton in Firestore. Currently, I have:
Firestore-root
|
--- users
|
--- userid
|
---Would you like to participate: yes
I want to store the response within another field in Firestore, similar to this example where I want to achieve the following structure in Firestore (i.e., Agreement should be expandable and store Would you like to participate: yes):
Firestore-root
|
--- users
|
--- userid
|
---Agreement:
Would you like to participate: yes
Below is the code I am working with for two radiobutton
Global:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference uidRef = db.collection("users").document(uid);
RadioGroup radioGroup;
RadioButton yesButton;
RadioButton noButton;
For the OnCreate,
yesButton = findViewById(R.id.a1);
noButton = findViewById(R.id.a2);
radioGroup = findViewById(R.id.radioGroup);
String yes = yesButton.getText().toString();
String no = yesButton.getText().toString();
addSnapshotListener to listen the changes
uidRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(@Nullable DocumentSnapshot snapshot, @Nullable FirebaseFirestoreException e) {
if (e != null) {
Log.w(TAG, "Listen failed.", e);
return;
}
if (snapshot != null && snapshot.exists()) {
String participate = snapshot.getString("Would you like to participate");
if (participate != null) {
yesButton.setChecked(true);
} else {
noButton.setChecked(true);
}
}
}
});
The two radio buttons:
yesButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (yesButton.isChecked()) {
Map<String, Object> update = new HashMap<>();
update.put("Would you like to participate", yes);
uidRef.update(update).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Response updated ", Toast.LENGTH_SHORT).show();
}
});
}
}
});
noButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (noButton.isChecked()) {
Map<String, Object> update = new HashMap<>();
update.put("Would you like to participate", no);
uidRef.update(update).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(getApplicationContext(), "Response updated ", Toast.LENGTH_SHORT).show();
}
});
}
}
});
I tried with Arrays.asList on update.put("Would you like to participate", Arrays.asList(yes));, it will make the structure in Firestore but still does not achieve my goal:
"Would you like to participate":
0: Yes
Thank you in advance!