0

I am creating a MCQ app using recylerview where I have questions, 4 radio button and submit buttons. My program also has correct answer when submit click radio button and click submit button and if answer is correct I change the correct radio button background with green and red for wrong answer.

Now problem is that there are multiple questions with multiple submit buttons when I click first question correct radio button it changes its background red, same for all questions but except for last.

For last questions it gives correct background for correct and incorrect answer

Gif of my problem: https://ibb.co/LzQSVNz

In gif in first question ww2 is correct, but code changed its color to red and 2nd questions which is last is giving correct results.

My layout code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_marginTop="10dp"
    android:layout_width="match_parent"
    android:background="@color/white"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:background="@color/white"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:weightSum="2"
            android:id="@+id/newlinear1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:layout_weight="1"
                android:id="@+id/question"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/question"
                android:textColor="@color/black"
                android:textAllCaps="true"
                android:textAlignment="center"
                android:textStyle="bold">

            </TextView>

            <ImageView
                android:layout_gravity="center"
                android:visibility="gone"
                android:src="@mipmap/ic_launcher_round"
                android:layout_weight="1"
                android:id="@+id/QuestionImage"
                android:layout_width="match_parent"
                android:layout_height="300dp">

            </ImageView>

        </LinearLayout>

        <LinearLayout
            android:background="@drawable/linear"
            android:id="@+id/linear2"
            android:layout_marginTop="10dp"
            android:layout_below="@id/newlinear1"
            android:layout_width="match_parent"
            android:layout_margin="40dp"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center">

            <RadioGroup
                android:id="@+id/radioPostGroup"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <RadioButton
                    android:layout_marginTop="25dp"
                    android:textColor="@color/black"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/answer1"
                    android:id="@+id/radioAnswer1">

                </RadioButton>
                <RadioButton
                    android:layout_marginTop="25dp"
                    android:textColor="@color/black"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/answer2"
                    android:id="@+id/radioAnswer2">

                </RadioButton>
                <RadioButton
                    android:layout_marginTop="25dp"
                    android:textColor="@color/black"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/answer3"
                    android:id="@+id/radioAnswer3">

                </RadioButton>
                <RadioButton
                    android:layout_marginTop="25dp"
                    android:textColor="@color/black"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="@string/answer4"
                    android:id="@+id/radioAnswer4">

                </RadioButton>


            </RadioGroup>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/linear3"
            android:layout_below="@id/linear2"
            android:orientation="horizontal"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">

            <Button
                android:id="@+id/submitAnswer"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Submit">

            </Button>
<!--            <View-->
<!--                -->
<!--                android:layout_width="fill_parent"-->
<!--                android:layout_weight="2"-->
<!--                android:layout_height="10dp"-->
<!--                android:layout_marginTop="0.5dp"-->
<!--                android:background="@color/purple"/>-->

        </LinearLayout>

        <LinearLayout
            android:id="@+id/mylinear4"
            android:layout_below="@id/linear3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >

            <com.like.LikeButton
                android:layout_weight="1"
                app:icon_type="heart"
                app:icon_size="10dp"
                android:id="@+id/myheart"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

            </com.like.LikeButton>

            <com.like.LikeButton
                android:layout_weight="1"
                app:icon_type="thumb"
                app:icon_size="10dp"
                android:id="@+id/mythumb"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

            </com.like.LikeButton>

            <com.like.LikeButton
                android:layout_weight="1"
                app:icon_type="star"
                app:icon_size="10dp"
                android:id="@+id/myStar"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

            </com.like.LikeButton>

        </LinearLayout>
        <View
            android:layout_below="@+id/mylinear4"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/black">

        </View>

    </RelativeLayout>

    </RelativeLayout>

my recyclerview:

package com.example.mcqapp.activities.Adapters;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.mcqapp.R;
import com.example.mcqapp.activities.Models.RequestDataModel;
import com.example.mcqapp.activities.Models.RetrieveModel;
import com.example.mcqapp.activities.forms.QuestionData;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.like.LikeButton;
import com.like.OnLikeListener;

import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Text;

import java.util.HashMap;
import java.util.List;

public class finalAdapter extends RecyclerView.Adapter<finalAdapter.MyHolder> {
    private List<QuestionData> dataset;
    private Context context;
    private DatabaseReference heartReference;
    private int counter = 0;
    boolean testCick = false;
    private RadioButton radioButton;
    private String CorrectAnswer;


    public finalAdapter(List<QuestionData> dataset,Context context){
        this.dataset = dataset;
        this.context = context;

    }


    @NotNull
    @Override
    public MyHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.recyclerquestions,parent,false);
        
        MyHolder myHolder = new MyHolder(view);

        return myHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull finalAdapter.MyHolder holder, int position) {
        holder.question.setText(dataset.get(position).getQuestion());
        holder.radioButton1.setText(dataset.get(position).getAnswer1());
        holder.radioButton2.setText(dataset.get(position).getAnswer2());
        holder.radioButton3.setText(dataset.get(position).getAnswer3());
        holder.radioButton4.setText(dataset.get(position).getAnswer4());

        CorrectAnswer  = dataset.get(position).getCorrectAnswer();

        String im = dataset.get(position).getImageLink();
        if (im != null){
            holder.imageView.setVisibility(View.VISIBLE);
            Glide.with(context).load(dataset.get(position).getImageLink()).into(holder.imageView);
        }

        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        String userID = firebaseUser.getUid();
        Log.d("userid", "onBindViewHolder: "+ userID);

        String posKey = dataset.get(position).getKey();

//        final FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance().getReference("likes");

//        final DatabaseReference databaseReference = mFirebaseDatabase.getReference("Questions").child(dataset.get(position).getGroup()).child(dataset.get(position).getKey());
        holder.getheartButtonStatus(posKey,userID);

        DatabaseReference likesReference = FirebaseDatabase.getInstance().getReference("Likes");

//        HashMap<String, Object> result = new HashMap<>();

        holder.heart.setOnLikeListener(new OnLikeListener() {
            @Override
            public void liked(LikeButton likeButton) {
                testCick = true;
                likesReference.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
                        if (testCick==true){
                            if (snapshot.child(posKey).hasChild(userID)){
//                                likesReference.child(posKey).removeValue();
//                                holder.heart.setLiked(true);
                                testCick =false;

                            }else{
                                likesReference.child(posKey).child(userID).setValue(true);
                                testCick = false;
                            }
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull @NotNull DatabaseError error) {

                    }
                });



            }

            @Override
            public void unLiked(LikeButton likeButton) {
                likesReference.child(posKey).removeValue();
                testCick =false;
            }
        });


    }

    @Override
    public int getItemCount() {
        return dataset.size();
    }

    public class MyHolder extends RecyclerView.ViewHolder{
        TextView question;
        RadioButton radioButton1,radioButton2,radioButton3,radioButton4;
        ImageView imageView;
        LikeButton heart,thumb,star;
        RadioGroup radioGroup;

        private Button Button;
        public  MyHolder(View itemView){
            super(itemView);
            radioGroup =  itemView.findViewById(R.id.radioPostGroup);
            question = (TextView) itemView.findViewById(R.id.question);
            radioButton1 = itemView.findViewById(R.id.radioAnswer1);
            radioButton2 = itemView.findViewById(R.id.radioAnswer2);
            radioButton3 = itemView.findViewById(R.id.radioAnswer3);
            radioButton4 = itemView.findViewById(R.id.radioAnswer4);
            imageView = itemView.findViewById(R.id.QuestionImage);
            Button = itemView.findViewById(R.id.submitAnswer);
            heart= itemView.findViewById(R.id.myheart);
            thumb= itemView.findViewById(R.id.mythumb);
            star= itemView.findViewById(R.id.myStar);

            Button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int selectedId = radioGroup.getCheckedRadioButtonId();
                    Log.d("selected", "onClick: "+selectedId);
                    radioButton = itemView.findViewById(selectedId);
          //**`problem is in this section`**

                    Toast.makeText(context.getApplicationContext(),radioButton.getText(),Toast.LENGTH_LONG).show();

                    if(radioButton.getText().equals(CorrectAnswer)){
                        radioButton.setBackgroundColor(Color.parseColor("#9ded9f"));
                    }else{
                        radioButton.setBackgroundColor(Color.parseColor("#990e0e"));
                    }


                }
            });

        }

        public void getheartButtonStatus(String posKey, String userID) {
            heartReference = FirebaseDatabase.getInstance().getReference("Likes");
            heartReference.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull @NotNull DataSnapshot snapshot) {
                    if (snapshot.child(posKey).hasChild(userID)){
                        int likeCount = (int)snapshot.child(posKey).getChildrenCount();
                        heart.setLiked(true);
                    }
                }

                @Override
                public void onCancelled(@NonNull @NotNull DatabaseError error) {

                }
            });


        }
    }

}

Already read

Radiogroup in recyclerview

Display RadioGroup in ListView

Radiogroup in recyclerview incorrect

halfer
  • 19,824
  • 17
  • 99
  • 186
James
  • 1,124
  • 3
  • 17
  • 37

1 Answers1

1

Every time you bind data to a viewholder, you are setting CorrectAnswer to a value. The problem is that there is only one CorrectAnswer for all your viewholders and it contains the last value bound which could be anything that is displayed and a few that are not.

You can solve this problem by associating the correct answer with each viewholder by using a variable within the viewholder or fetching the answer from the array based upon position.

For example, in MyHolder define a member variable as follows:

String correctAnswer;

Remove the global CorrectAnswer variable.

Then, in onBindViewHolder() set the variable like this:

holder.correctAnswer  = dataset.get(position).getCorrectAnswer();

Now, in the click listener, you can check for the correct answer to the question being asked. Each MyHolder contains the answer to the question it represents.

if(radioButton.getText().equals(correctAnswer)){
    radioButton.setBackgroundColor(Color.parseColor("#9ded9f"));
} else {
    radioButton.setBackgroundColor(Color.parseColor("#990e0e"));
                }
Cheticamp
  • 61,413
  • 10
  • 78
  • 131
  • for array based i need position inside MyHolder class ? how can i get that? and how to mplement "associating the correct answer with each viewholder by using a variable within the viewholder". Can you please show me an example? – James Jul 09 '21 at 06:46
  • It's working. Great . Thank you so much sir, i got confused but you solved my confusion. – James Jul 09 '21 at 12:22
  • Remember when you are working with recyclerview. if you do something with if() then you must remove it with else() on onBindViewHolder(). otherwise, there will always be a problem. Wrong position will be selected when you scroll. – Rohaitas Tanoli Aug 13 '21 at 19:18