My radio button does not work when selected

61 Views Asked by At

I was making a quiz, initially it was successful when the answer choices were only "Option 1, Option 2, Option 3" and the correct answer was for example "Option 2" but when I changed the answer choices and the answer was correct, my quiz application had a problem where it didn't display the questions and when choose an answer between 3 options, where in my application a statement like this "please choose an answer" appears. Please help, maybe I made a mistake in coding. thank you

This is my Quiz Activity

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Timer;

public class quizmateri2Activity extends AppCompatActivity {
    private TextView tvQuestion, tvTimer, tvScore;
    private RadioGroup rgAnswers;
    private Button btnSubmit;

    private Question2[] questions;
    private int currentQuestionIndex = 0;
    private int score;
    private CountDownTimer countDownTimer;
    private long timeLeftInMillis;
    private static final long COUNTDOWN_IN_MILLIS = 60000;
    public static final String extra_score = "extraScore";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quizmateri2);

        // Inisialisasi widget
        tvQuestion = findViewById(R.id.tv_question);
        tvTimer = findViewById(R.id.tv_timer);
        tvScore = findViewById(R.id.tv_score);
        rgAnswers = findViewById(R.id.rg_answers);
        btnSubmit = findViewById(R.id.next2);


        // Inisialisasi waktu awal
        timeLeftInMillis = COUNTDOWN_IN_MILLIS;
        // Mulai timer
        startCountDown();

        // Masukkan soal dan jawaban ke dalam list questions
        questions = new Question2[]{
                    new Question2("Bahasa Ternate dari kata'Saya' untuk laki-laki adalah...", new String[]{"Fajaru", "Fangare", "Ngom"}, "Fangare"),
                    new Question2("Arti dari kata 'Tufa' adalah...", new String[]{"Langit", "Matahari", "Awan"}, "Langit"),
                    new Question2("Arti dari kalimat 'Nonau se fofoeka' adalah...", new String[]{"Anak-anak dan remaja", "Laki-laki dan perempuan", "Orangtua dan anak"}, "Laki-laki dan perempuan"),
                    new Question2("Bahasa Ternate dari kata 'Mandi' adalah...", new String[]{"Tego", "Tagi", "Mahodo"}, "Mahodo"),
                    new Question2("Bahasa Ternate dari kata 'Duduk' adalah...", new String[]{"Mahodo", "Tagi", "Tego"}, "Tego"),
                    new Question2("Arti dari kata 'Sahu' adalah...", new String[]{"Kecil", "Panas", "Jauh"}, "Panas"),
                    new Question2("Bahasa Ternate dari kata 'Dia' untuk perempuan adalah...", new String[]{"Mina", "Ana", "Una"}, "Mina"),
                    new Question2("Arti dari kata 'Raga-raga' adalah...", new String[]{"Betis", "Jari-jari", "Usus"}, "Jari-jari"),
                    new Question2("Bahasa Ternate dari kata 'Nyao osu' adalah...", new String[]{"Ikan goreng", "Ikan mentah", "Ikan bakar"}, "Ikan bakar"),
                    new Question2("Bahasa Ternate dari kalimat 'Anjing itu beranak empat ekor' adalah...", new String[]{"Namo enage mangofa ngai rara", "Kaso enage mangofa ngai raha", "Kaso enage mangofa ngai rara"}, "Kaso enage mangofa ngai raha"),

        };


        //load pertanyaan pertama
        loadQuestion(currentQuestionIndex);


        // Menambahkan event listener pada tombol submit
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkAnswer();
            }
        });
    }

    private void startCountDown() {
        countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timeLeftInMillis = millisUntilFinished;
                updateCountDownText();
            }

            @Override
            public void onFinish() {
                timeLeftInMillis = 0;
                updateCountDownText();
                checkAnswer();
            }
        }.start();
    }

    private void updateCountDownText() {
        int minutes = (int) (timeLeftInMillis / 1000) / 60;
        int seconds = (int) (timeLeftInMillis / 1000) % 60;

        String timeLeftFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
        tvTimer.setText(timeLeftFormatted);
    }

    private void loadQuestion(int questionIndex) {

        // set text pertanyaan
        tvQuestion.setText("Soal " + (questionIndex + 1));

        // reset pilihan jawaban
       rgAnswers.clearCheck();

        // set pilihan jawaban
        RadioButton option1 = findViewById(R.id.option1);
        RadioButton option2 = findViewById(R.id.option2);
        RadioButton option3 = findViewById(R.id.option3);

        option1.setText(questions[questionIndex].getOptions()[0]);
        option2.setText(questions[questionIndex].getOptions()[1]);
        option3.setText(questions[questionIndex].getOptions()[2]);
    }

    private void checkAnswer() {
        // jawaban user
        int selectedId = rgAnswers.getCheckedRadioButtonId();
        RadioButton selectedRadioButton = findViewById(selectedId);

        if (selectedRadioButton != null) {
            String selectedAnswer = selectedRadioButton.getText().toString();
            String correctAnswer = questions[currentQuestionIndex].getCorrectAnswer();

            if (selectedAnswer.equals(correctAnswer)) {
                score++;
                tvScore.setText("Score: " + score);
                Toast.makeText(this, "Jawaban Anda benar!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "awaban Anda salah!", Toast.LENGTH_SHORT).show();
            }

            currentQuestionIndex++; // pindah soal berikut

            if (currentQuestionIndex < questions.length) {
                loadQuestion(currentQuestionIndex);

            } else {

                Toast.makeText(this, "Quiz selesai! Score Anda: " + score, Toast.LENGTH_SHORT).show();
                finishQuiz();
            }
        } else {
            Toast.makeText(this, "Silahkan pilih jawaban!", Toast.LENGTH_SHORT).show();
        }
    }

    private void finishQuiz() {
        Intent resultIntent = new Intent();
        resultIntent.putExtra(extra_score, score);
        setResult(RESULT_OK, resultIntent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

}

this is my Question2.java

import java.util.List;

public class Question2 {

    private String question;
    private String[] options;
    private String correctAnswer;

    public Question2(String question, String[] options, String correctAnswer) {
        this.question = question;
        this.options = options;
        this.correctAnswer = correctAnswer;
    }

    public String getQuestion() {
        return question;
    }

    public String[] getOptions() {
        return options;
    }

    public String getCorrectAnswer() {
        return correctAnswer;
    }

}

xml

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".quizmateri2Activity"
    android:background="@drawable/wpdaun">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="260dp"
        android:background="@drawable/soalbg"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_timer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="10dp"
            android:text="00.00"
            android:textColor="@color/white"
            android:textSize="25sp"/>
        <TextView
            android:id="@+id/tv_score"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="130dp"
            android:layout_marginTop="10dp"
            android:text="Score: 0"
            android:textColor="@color/white"
            android:textSize="25sp"/>
    </LinearLayout>

    <TextView
        android:id="@+id/tv_question"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="25dp"
        android:layout_marginTop="100dp"
        android:text="Soal"
        android:textColor="@color/white"
        android:textStyle="bold"
        android:textSize="20sp"/>
    <RadioGroup
        android:id="@+id/rg_answers"
        android:layout_width="match_parent"
        android:layout_height="272dp"
        android:layout_below="@+id/tv_question"
        android:layout_marginTop="140dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="20dp"
        android:elevation="5dp">

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            app:cardCornerRadius="10dp"
            android:elevation="10dp"
            android:background="@drawable/bg_button">

        <RadioButton
            android:id="@+id/option1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:elevation="5dp"
            android:background="@drawable/optiondesain"
            android:freezesText="true"
            android:padding="16dp"
            android:text="Option 1" />
        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            app:cardCornerRadius="10dp"
            android:elevation="10dp"
            android:background="@drawable/bg_button">

        <RadioButton
            android:id="@+id/option2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:elevation="5dp"
            android:background="@drawable/optiondesain"
            android:freezesText="true"
            android:padding="16dp"
            android:text="Option 2" />
        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="15dp"
            app:cardCornerRadius="10dp"
            android:elevation="10dp"
            android:background="@drawable/bg_button">

        <RadioButton
            android:id="@+id/option3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:elevation="5dp"
            android:background="@drawable/optiondesain"
            android:freezesText="true"
            android:padding="16dp"
            android:text="Option 3" />
        </androidx.cardview.widget.CardView>

    </RadioGroup>

    <Button
        android:id="@+id/next2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rg_answers"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:text="SELANJUTNYA"
        android:textSize="20sp"/>

</RelativeLayout>

Here's my quiz application

enter image description here

1

There are 1 best solutions below

0
Miroslav Hýbler On

RadioButton has to be direct child of RadioButtonGroup to work, if you remove the cardView you can see it will work fine.

Updated activity_quizmateri2.xml

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".quizmateri2Activity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="260dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_timer"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="25dp"
            android:layout_marginTop="10dp"
            android:text="00.00"
            android:textColor="@color/white"
            android:textSize="25sp"/>
        <TextView
            android:id="@+id/tv_score"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="130dp"
            android:layout_marginTop="10dp"
            android:text="Score: 0"
            android:textColor="@color/white"
            android:textSize="25sp"/>
    </LinearLayout>

    <TextView
        android:id="@+id/tv_question"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_marginLeft="25dp"
        android:layout_marginRight="25dp"
        android:layout_marginTop="100dp"
        android:text="Soal"
        android:textColor="@color/white"
        android:textStyle="bold"
        android:textSize="20sp"/>

    <RadioGroup
        android:id="@+id/rg_answers"
        android:layout_width="match_parent"
        android:layout_height="272dp"
        android:layout_below="@+id/tv_question"
        android:layout_marginTop="140dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:padding="20dp"
        android:elevation="5dp">



            <RadioButton
                android:id="@+id/option1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:elevation="5dp"
                android:freezesText="true"
                android:padding="16dp"
                android:text="Option 1" />


            <RadioButton
                android:id="@+id/option2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:elevation="5dp"
                android:freezesText="true"
                android:padding="16dp"
                android:text="Option 2" />

            <RadioButton
                android:id="@+id/option3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:elevation="5dp"
                android:freezesText="true"
                android:padding="16dp"
                android:text="Option 3" />

    </RadioGroup>

    <Button
        android:id="@+id/next2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/rg_answers"
        android:layout_marginLeft="50dp"
        android:layout_marginRight="50dp"
        android:text="SELANJUTNYA"
        android:textSize="20sp"/>

</RelativeLayout>