Save and update radiobutton response correctly java

Viewed 91

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

To solve this, first, you have to create a layout that contains two radio buttons:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <RadioButton
            android:id="@+id/yesRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Yes"/>

        <RadioButton
            android:id="@+id/noRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="No"/>
    </RadioGroup>
</androidx.constraintlayout.widget.ConstraintLayout>

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:

Firestore-root
  |
  --- users
       |
       --- $uid
            |
            --- participate: true
            |
            --- //other fields

Here is the code:

Define them as members of the class (global variables):

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore db = FirebaseFirestore.getInstance();
DocumentReference uidRef = db.collection("users").document(uid);

Add inside onCreate:

RadioButton yesRadioButton = findViewById(R.id.yesRadioButton);
RadioButton noRadioButton = findViewById(R.id.noRadioButton);
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()) {
            Boolean participate = snapshot.getBoolean("participate");
            if(participate != null) {
                if (participate) {
                    yesRadioButton.setChecked(true);
                } else {
                    noRadioButton.setChecked(true);
                }
            }
        }
    }
});

Here is to code for attaching a click listener on each radio button:

yesRadioButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (yesRadioButton.isChecked()) {
            updateParticipate(true);
        }
    }
});
noRadioButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (noRadioButton.isChecked()) {
            updateParticipate(false);
        }
    }
});

And here is the method which is responsible for the update:

void updateParticipate(boolean participate) {
    Map<String, Object> update = new HashMap<>();
    update.put("participate", participate);
    uidRef.update(update).addOnCompleteListener(new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            Toast.makeText(getApplicationContext(), "Updated: " + participate, Toast.LENGTH_SHORT).show();
        }
    });
}

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.

Related