Home > Software engineering >  I need to hide a radio button in a quiz app android
I need to hide a radio button in a quiz app android

Time:01-06

I would like to ask for some help with my android code. I am trying to develop a quiz app using SQLite.Number of possible answers differs so i need to hide radio buttons from the main screen if answers e.g. are 3 and not 4 (4 is by default the number of the radio buttons). Tried to use:

if (DataContract.QuestionTable.COLUMN_ANSWER4.isEmpty ()){ radioButton4.setVisibility (View.INVISIBLE); }

but does not seem to work.I'm new in android programming and this is my first project so every comment will be very helpful. Thank you.

Here is part of my code:

xml of Quiz Activity

`<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#C8ECF1"
android:backgroundTint="#C2ECF1"
android:backgroundTintMode="src_atop"
android:fadingEdge="horizontal"
tools:context=".QuestionsAct">

<TextView
    android:id="@ id/tvQuestionCount"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="5dp"
    android:layout_marginTop="5dp"
    android:text="question 1/x"
    android:textAlignment="center"
    android:textStyle="bold"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@ id/tVTime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:layout_marginEnd="16dp"
    android:text="30:00"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<RadioGroup
    android:id="@ id/radioGroup"
    android:layout_width="356dp"
    android:layout_height="202dp"
    android:layout_marginBottom="40dp"
    app:layout_constraintBottom_toTopOf="@ id/butConfirmAns"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.29"
    app:layout_constraintStart_toStartOf="parent">

    <RadioButton
        android:id="@ id/radioButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:hint="answear1"
        android:textAlignment="viewStart"
        android:textStyle="bold" />

    <RadioButton
        android:id="@ id/radioButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:hint="answer2"
        android:textAlignment="viewStart"
        android:textStyle="bold" />

    <RadioButton
        android:id="@ id/radioButton3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:hint="answer3"
        android:textAlignment="viewStart"
        android:textStyle="bold" />

    <RadioButton
        android:id="@ id/radioButton4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="24dp"
        android:textAlignment="viewStart"
        android:textStyle="bold"

        />

</RadioGroup>

<TextView
    android:id="@ id/tVQuestion"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:text="Question bla bla "
    android:textSize="20sp"
    app:layout_constraintBottom_toTopOf="@ id/radioGroup"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@ id/tvImgQuest"
    app:layout_constraintVertical_bias="0.139" />

<Button
    android:id="@ id/butConfirmAns"
    android:layout_width="wrap_content"
    android:layout_height="35dp"
    android:layout_marginStart="15dp"
    android:layout_marginBottom="36dp"
    android:background="#FF9800"
    android:text="Submit"
    android:textColor="#009688"
    android:textSize="12sp"
    android:textStyle="bold"
    app:iconTint="#DA9E45"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toEndOf="@ id/butBack"
    app:strokeColor="#8BC34A" />

<ImageView
    android:id="@ id/tvImgQuest"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:visibility="visible"

    app:layout_constraintBottom_toTopOf="@ id/radioGroup"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.176"
    app:srcCompat="@drawable/ic_launcher_background" />

<Button
    android:id="@ id/butBack"
    android:layout_width="61dp"
    android:layout_height="33dp"
    android:layout_marginStart="4dp"
    android:layout_marginBottom="36dp"
    android:textSize="12sp"
    app:icon="@android:drawable/ic_media_rew"
    app:iconTint="#2196F3"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@ id/butForw"
    android:layout_width="61dp"
    android:layout_height="35dp"
    android:layout_marginStart="15dp"
    android:layout_marginBottom="36dp"
    android:textSize="12sp"
    android:textStyle="bold"
    app:icon="@android:drawable/ic_media_ff"
    app:iconTint="#2196F3"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toEndOf="@ id/butConfirmAns" />

<Button
    android:id="@ id/butFinish"
    android:layout_width="85dp"
    android:layout_height="35dp"
    android:layout_marginStart="30dp"
    android:layout_marginEnd="10dp"
    android:layout_marginBottom="36dp"
    android:text="Finish"
    android:textAlignment="center"
    android:textColor="#F44336"
    android:textSize="10sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toEndOf="@ id/butForw" />

<TextView
    android:id="@ id/tvScore"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="4dp"
    android:layout_marginTop="28dp"
    android:text="Score: 0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@ id/tvQuestionCount" />

   </androidx.constraintlayout.widget.ConstraintLayout>`

Tables of Database

 `package com.anna.myquiz;
  import android.provider.BaseColumns;
  public final class DataContract {
  private  DataContract(){}
  public static class StudentTable implements BaseColumns {

    public static final String TABLE_NAME1 = "student_info";
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_AM = "studentAm";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_SEMESTER = "semester";
    public static final String COLUMN_SCORE = "score";
    public static final String COLUMN_DATE = "studentDate";
}
public static class QuestionTable implements BaseColumns {
    public static final String TABLE_NAME = "quiz_question";
    public static final String COLUMN_QUESTION = "question";
    public static final String COLUMN_IMAGE = "image";
    public static final String COLUMN_ANSWER1 = "answer1";
    public static final String COLUMN_ANSWER2 = "answer2";
    public static final String COLUMN_ANSWER3 = "answer3";
    public static final String COLUMN_ANSWER4 = "answer4";
    public static final String COLUMN_ANSWERNUM = "answerNum";

}
}`

Database SQLiteHelper

`package com.anna.myquiz;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.View;

import com.anna.myquiz.DataContract.*;
import java.util.ArrayList;
import java.util.List;

public class DataDbHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "Quiz.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase db;

public DataDbHelper (Context context) {
    super (context, DATABASE_NAME, null, DATABASE_VERSION);
}


@Override
public void onCreate (SQLiteDatabase db) {

    this.db = db;
    final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE "  
            QuestionTable.TABLE_NAME   " ( "  
            QuestionTable._ID   " INTEGER PRIMARY KEY AUTOINCREMENT,"  
            QuestionTable.COLUMN_QUESTION   " TEXT,"  
            QuestionTable.COLUMN_IMAGE   " TEXT,"  
            QuestionTable.COLUMN_ANSWER1   " TEXT,"  
            QuestionTable.COLUMN_ANSWER2   " TEXT,"  
            QuestionTable.COLUMN_ANSWER3   " TEXT,"  
            QuestionTable.COLUMN_ANSWER4   " TEXT,"  
            QuestionTable.COLUMN_ANSWERNUM   " INTEGER "  
            ")";

    db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
    fillQuestionsTable();

    final String SQL_CREATE_STUDENT_TABLE = "CREATE TABLE "  
            StudentTable.TABLE_NAME1   " ( "  
            StudentTable.COLUMN_ID   " INTEGER PRIMARY KEY AUTOINCREMENT,"  
            StudentTable.COLUMN_AM   " TEXT,"  
            StudentTable.COLUMN_NAME   " TEXT,"  
            StudentTable.COLUMN_SEMESTER   " TEXT,"  
            StudentTable.COLUMN_SCORE   " TEXT, "  
            StudentTable.COLUMN_DATE   " TEXT "  
           ")";
    db.execSQL(SQL_CREATE_STUDENT_TABLE);

}


@Override
public void onUpgrade (SQLiteDatabase db, int oldVersion, int   newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "   QuestionTable.TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS "   StudentTable.TABLE_NAME1);
    onCreate(db);

}
private void fillQuestionsTable() {
    Question q1 = new Question ("A is correct","arkas.jpj",  "Maria" ,"anna", "Nikos" , "Andy", 1);
    addQuestion (q1);
    Question q2 = new Question ("B is correct","arkas1.jpg", "kjbhkjhA" ,"Bkjgkgj", "Cjvjhgj" , null, 2);
    addQuestion (q2);
    Question q3 = new Question ("C is correct","arkas2.jpg", "cgxcvnx" ,"xcvnxvxv", "Cgnhxfgjxf" , null, 3);
    addQuestion (q3);
    Question q4 = new Question ("A is correct again","NULL", "fvjxfvA" ,"Bxfgxmg", "Cxgmxmx" , null, 1);
    addQuestion (q4);
    Question q5 = new Question ("D is correct","NULL", "Afghf" ,"fghxggggghB", "xfgxghxghC" , "fghxghxgh", 4);
    addQuestion (q5);

}
private void addQuestion(Question question){
    ContentValues cv = new ContentValues();
    cv.put(QuestionTable.COLUMN_QUESTION, question.getQuestion());
    cv.put(QuestionTable.COLUMN_IMAGE, String.valueOf (question.getImage()));
    cv.put(QuestionTable.COLUMN_ANSWER1, question.getAnswer1());
    cv.put(QuestionTable.COLUMN_ANSWER2, question.getAnswer2());
    cv.put(QuestionTable.COLUMN_ANSWER3, question.getAnswer3());

    cv.put(QuestionTable.COLUMN_ANSWER4, question.getAnswer4());
    cv.put(QuestionTable.COLUMN_ANSWERNUM, question.getAnswerNum());
    db.insert(QuestionTable.TABLE_NAME, null, cv);
}

// this method is use to add new student to our sqlite database.
public void addNewStudent(String studentAm, String studentName, String studentSemester, int studentScore, String studentDate){

    // on below line we are creating a variable for
    // our sqlite database and calling writable method
    // as we are writing data in our database.
    SQLiteDatabase db = this.getWritableDatabase();

    // on below line we are creating a
    // variable for content values.
    ContentValues values = new ContentValues();


    // on below line we are passing all values
    // along with its key and value pair.
    values.put(StudentTable.COLUMN_AM, studentAm);
    values.put(StudentTable.COLUMN_NAME, studentName);
    values.put(StudentTable.COLUMN_SEMESTER, studentSemester);
    values.put(StudentTable.COLUMN_SCORE, studentScore);
    values.put(StudentTable.COLUMN_DATE, studentDate);

    // after adding all values we are passing
    // content values to our table.
    db.insert(StudentTable.TABLE_NAME1, null, values);

    // at last we are closing our
    // database after adding database.
    db.close();
}

public  ArrayList<Student> readStudentInfo () {
    // on below line we are creating a
    // database for reading our database.
    SQLiteDatabase db = this.getReadableDatabase();

    // on below line we are creating a cursor with query to read data from database.
    Cursor cursorCourses = db.rawQuery("SELECT * FROM "   StudentTable.TABLE_NAME1, null);

    // on below line we are creating a new array list.
    ArrayList<Student> StudentArrayList = new ArrayList<>();

    // moving our cursor to first position.
    if (cursorCourses.moveToFirst()) {
        do {
            // on below line we are adding the data from cursor to our array list.
            StudentArrayList.add(new Student(cursorCourses.getString(1),
                    cursorCourses.getString(5),
                    cursorCourses.getString(4),
                    cursorCourses.getString(2),
                    cursorCourses.getString(3)));
        } while (cursorCourses.moveToNext());
        // moving our cursor to next.
    }
    // at last closing our cursor
    // and returning our array list.
    cursorCourses.close();
    return StudentArrayList;
}

public List<Question> getAllQuestions() {
    List<Question> questionList = new ArrayList<>();
    db = getReadableDatabase ();
    // Choose Random Questions
    Cursor c = db.rawQuery("SELECT * FROM quiz_question ORDER BY RANDOM() LIMIT 3 ",null );


    if (c.moveToFirst()){
        do {
            Question question = new Question();
            question.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_QUESTION)));
            question.setImage (c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_IMAGE)));
            question.setAnswer1(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWER1)));
            question.setAnswer2(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWER2)));
            question.setAnswer3(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWER3)));

            question.setAnswer4(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWER4)));
            question.setAnswerNum (c.getInt(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWERNUM)));
            questionList.add (question);
        } while (c.moveToNext());
    }
    c.close ();
    return questionList;
}

public  void addScore(int StudentScore){
    ContentValues cv = new ContentValues();
    cv.put(DataContract.StudentTable.COLUMN_SCORE, StudentScore);
    db.update(DataContract.StudentTable.TABLE_NAME1, cv, DataContract.StudentTable.COLUMN_SCORE   "= ?", new String[] {"?"});
    db.close();
}`

Question

`package com.anna.myquiz;

 import android.graphics.drawable.Drawable;

public class Question {
private String question;
private String image;
private String answer1;
private String answer2;
private String answer3;
private String answer4;
private int answerNum;

public Question() {}

public Question (String question,String image, String answer1,   String answer2, String answer3, String answer4, int answerNum) {
    this.question = question;
    this.image = image;
    this.answer1 = answer1;
    this.answer2 = answer2;
    this.answer3 = answer3;
    this.answer4 = answer4;
    this.answerNum = answerNum;
}

public String getQuestion () {
    return question;
}

public void setQuestion (String question) {
    this.question = question;
}

public Object getImage () {
    return Drawable.createFromPath (image);
}

public void setImage (String image) {
    this.image = image;
}

public String getAnswer1 () {
    return answer1;
}

public void setAnswer1 (String answer1) {
    this.answer1 = answer1;
}

public String getAnswer2 () {
    return answer2;
}

public void setAnswer2 (String answer2) {
    this.answer2 = answer2;
}

public String getAnswer3 () {
    return answer3;
}

public void setAnswer3 (String answer3) {
    this.answer3 = answer3;
}

public String getAnswer4 () {
    return answer4;
}

public void setAnswer4 (String answer4) {
    this.answer4 = answer4;
}

public int getAnswerNum () {
    return answerNum;
}

public void setAnswerNum (int answerNum) {
    this.answerNum = answerNum;
}
}`

Student info

`package com.anna.myquiz;

public class Student {
private  String studentAm;
private String studentName;
private  String studentSemester;
private static int studentScore;
private String studentDate;
private int id;

public Student(){}

 public Student (String studentAm, String studentName, String      studentSemester, int studentScore, String studentDate, int id) {
    this.studentAm = studentAm;
    this.studentName = studentName;
    this.studentSemester = studentSemester;
    this.studentScore = studentScore;
    this.studentDate = studentDate;
    this.id = id;
}

public Student (String studentAm, String studentName, String   studentSemester, String studentScore, String studentDate) {
}

public String getStudentAm () {
    return studentAm;
}

public void setStudentAm (String studentAm) {
    this.studentAm = studentAm;
}

public String getStudentName () {
    return studentName;
}

public void setStudentName (String studentName) {
    this.studentName = studentName;
}

public String getStudentSemester () {
    return studentSemester;
}

public void setStudentSemester (String studentSemester)   {this.studentSemester = studentSemester; }

public static int getStudentScore () {
    return studentScore;
}

public void setStudentScore (int studentScore) {
    this.studentScore = studentScore;
}

public String getStudentDate () { return studentDate; }

public void setStudentDate (String studentDate) {   this.studentDate = studentDate; }

public int getId () {
    return id;
}

public void setId (int id) {
    this.id = id;
}
}`

Quiz Activity

 `package com.anna.myquiz;

  import androidx.appcompat.app.AppCompatActivity;


  import android.content.Intent;
  import android.content.res.ColorStateList;

  import android.database.sqlite.SQLiteDatabase;
  import android.graphics.drawable.Drawable;
   import android.os.CountDownTimer;
   import android.os.Bundle;
 import android.view.View;
 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 java.util.ArrayList;
 import java.util.Collections;
 import android.graphics.Color;
  import android.os.CountDownTimer;
  import java.util.Collections;
  import java.util.Locale;


public class QuestionsAct extends AppCompatActivity {

private TextView tvQuestion;
private TextView tvQuestionCount;
private TextView tvTime;
private TextView tvScore;
private RadioGroup radioGroup;
private RadioButton radioButton1;
private RadioButton radioButton2;
private RadioButton radioButton3;
private RadioButton radioButton4;
private Button butconfirmAns;
private Button butFinish;
private Button butForw;
private Button butBack;
private ImageView tvImgQuest;
private ColorStateList textColorDefaultRb;
private ColorStateList textColorDefaultCd;
private ArrayList<Question> questionList;
private ArrayList<Student> studentList;
private int questionCounter;
private int questionCountTotal;
private Question currentQuestion;
private int score;
private boolean answered;
private SQLiteDatabase db;
//-----------score variables---------------
public static final String EXTRA_SCORE = "extraScore";
//--------------time variables---------------------------
private static final long COUNTDOWN_IN_MILLIS = 3600000;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;


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

    tvQuestion = findViewById (R.id.tVQuestion);
    tvQuestionCount = findViewById (R.id.tvQuestionCount);
    tvTime = findViewById (R.id.tVTime);
    tvScore = findViewById (R.id.tvScore);
    radioGroup = findViewById (R.id.radioGroup);
    radioButton1 = findViewById (R.id.radioButton1);
    radioButton2 = findViewById (R.id.radioButton2);
    radioButton3 = findViewById (R.id.radioButton3);

    radioButton4 = findViewById (R.id.radioButton4);
    butconfirmAns =  findViewById (R.id.butConfirmAns);
    butForw = findViewById (R.id.butForw);
    butBack = findViewById (R.id.butBack);
    tvImgQuest = findViewById (R.id.tvImgQuest);
    textColorDefaultRb = radioButton1.getTextColors ();
    textColorDefaultCd = tvTime.getTextColors();

    DataDbHelper dbHelper = new DataDbHelper (this);
    questionList = (ArrayList<Question>)       bHelper.getAllQuestions ();
    questionCountTotal = questionList.size ();
    Collections.shuffle (questionList);
    timeLeftInMillis = COUNTDOWN_IN_MILLIS;
    startCountDown();
    showNextQuestion ();

    radioGroup.clearCheck();

    butconfirmAns.setOnClickListener (new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            if(!answered)
            {
                if (radioButton1.isChecked() ||   radioButton2.isChecked() || radioButton3.isChecked() || radioButton4.isChecked())
                {
                    checkAnswer();
                }
                else {
                    Toast.makeText (QuestionsAct.this, "Please select an answer", Toast.LENGTH_SHORT).show ();
                }
            }
            else {
                showNextQuestion ();
            }
        }
    });
}

private void showNextQuestion()
{
    radioButton1.setTextColor (textColorDefaultRb);
    radioButton2.setTextColor (textColorDefaultRb);
    radioButton3.setTextColor (textColorDefaultRb);
    radioButton4.setTextColor (textColorDefaultRb);
    radioGroup.clearCheck();
    Question question;

    if (questionCounter < questionCountTotal )
    {
        currentQuestion = questionList.get(questionCounter);

        tvQuestion.setText(currentQuestion.getQuestion ());
        tvImgQuest. setImageDrawable((Drawable)  currentQuestion.getImage());

        radioButton1.setText(currentQuestion.getAnswer1 ());
        radioButton2.setText(currentQuestion.getAnswer2 ());
        radioButton3.setText(currentQuestion.getAnswer3 ());
        //radioButton4.setText(currentQuestion.getAnswer4 ());
        if (DataContract.QuestionTable.COLUMN_ANSWER4.isEmpty ()){
            radioButton4.setVisibility (View.INVISIBLE);
        } else {
            radioButton4.setText(currentQuestion.getAnswer4 ());
         }
        questionCounter  ;
        tvQuestionCount.setText("Question: "   questionCounter   "/"   questionCountTotal);
        answered = false;
        butconfirmAns.setText("Submit");
    }
    else {
        finishQuiz();
    }

}

private void checkAnswer()
{
    answered = true;
    //countDownTimer.cancel();
    RadioButton rbSelected =  findViewById(radioGroup.getCheckedRadioButtonId());
    int answerNum = radioGroup.indexOfChild(rbSelected)   1;
    
    if (answerNum == currentQuestion.getAnswerNum()){
        score  ;
        tvScore.setText("Score: "   score);
    }
    // here must put the method to insert score in database
    checkEndOfQuiz();
}

private void checkEndOfQuiz()
{
    if (questionCounter < questionCountTotal)
    {
        butconfirmAns.setText("Next");
    }
    else {
        butconfirmAns.setText("Finish");
        //addScore(score);
    }
}


private void finishQuiz()
{
    Intent  ResultAct = new Intent(QuestionsAct.this,ResultAct.class);
    ResultAct.putExtra (EXTRA_SCORE , score);

    startActivity (ResultAct);
}


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 timeFormatted = String.format(Locale.getDefault(), "d:d", minutes, seconds);

    tvTime.setText(timeFormatted);

    if (timeLeftInMillis < 1000) {
        tvTime.setTextColor(Color.RED);
    } else {
        tvTime.setTextColor(textColorDefaultCd);
    }

}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (countDownTimer != null) {
        countDownTimer.cancel();
    }
}
}`

CodePudding user response:

Here's a demo with a suggested technique, considering the limited amount of code posted with the question.

This utilises two tables to conform with a normalised approach. A table for the questions and a table for answers. Each answer (the Children) has a link/map/relationship/association with a single Question (the Parent). To prevent referential integrity issues a Foreign Key constraint has been used.

First a few POJO's for the Questions, the Answers and QuestionWithAnswers (i.e. it's answers)

QuestionPOJO

class QuestionPOJO {
    long questionId;
    String questionText;

    public QuestionPOJO(long questionId, String questionText) {
        this.questionId = questionId;
        this.questionText = questionText;
    }

    public long getQuestionId() {
        return questionId;
    }

    public void setQuestionId(long questionId) {
        this.questionId = questionId;
    }

    public String getQuestionText() {
        return questionText;
    }

    public void setQuestionText(String questionText) {
        this.questionText = questionText;
    }
}

AnswerPOJO

class AnswerPOJO {
    long answerId;
    long questionMap;
    String answerText;
    boolean correct = false;

    public AnswerPOJO(long answerid, long questionMap, String answerText, boolean correct) {
        this.answerId = answerid;
        this.questionMap = questionMap;
        this.answerText = answerText;
        this.correct = correct;
    }

    public long getAnswerId() {
        return answerId;
    }

    public void setAnswerId(long answerId) {
        this.answerId = answerId;
    }

    public long getQuestionMap() {
        return questionMap;
    }

    public void setQuestionMap(long questionMap) {
        this.questionMap = questionMap;
    }

    public boolean isCorrect() {
        return correct;
    }

    public void setCorrect(boolean correct) {
        this.correct = correct;
    }

    public String getAnswerText() {
        return answerText;
    }

    public void setAnswerText(String answerText) {
        this.answerText = answerText;
    }
}

and QuestionWithAnswerPOJO

class QuestionWithAnswersPOJO {
    QuestionPOJO question;
    ArrayList<AnswerPOJO> answers = new ArrayList<>();

    public QuestionWithAnswersPOJO(QuestionPOJO question, List<AnswerPOJO> answers) {
        this.question = question;
        this.answers.clear();
        this.answers.addAll(answers);
    }

    public QuestionPOJO getQuestion() {
        return question;
    }

    public void setQuestion(QuestionPOJO question) {
        this.question = question;
    }

    public ArrayList<AnswerPOJO> getAnswers() {
        return answers;
    }

    public void setAnswers(ArrayList<AnswerPOJO> answers) {
        this.answers = answers;
    }
}

Now the DatabaseHelper, that handles all the database activity. Including methods to add and get Questions and the Answers and notably to get the Answers that belong to a question.

class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "questions.db";
    public static final int DATABASE_VERSION = 1;

    public static final String QUESTION_TABLE = "question";
    public static final String QUESTION_ID_COLUMN = BaseColumns._ID;
    public static final String QUESTION_TEXT_COLUMN = "question_text";
    public static final String ANSWER_TABLE = "answer";
    public static final String ANSWER_ID_COLUMN = BaseColumns._ID;
    public static final String ANSWER_TEXT_COLUMN = "answer_text";
    public static final String ANSWER_QUESTION_MAP_COLUMN = "question_map";
    public static final String ANSWER_CORRECT_COLUMN = "correct";

    private static volatile DatabaseHelper instance = null;
    private DatabaseHelper(Context context) {
        super(context,DATABASE_NAME,null,DATABASE_VERSION);
    }

    private static SQLiteDatabase db = null;

    public static DatabaseHelper getInstance(Context context, boolean forceOpen) {
        if (instance == null) {
            instance = new DatabaseHelper(context);
        }
        if (forceOpen) {
            db = instance.getWritableDatabase();
        }
        return instance;
    }
    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE IF NOT EXISTS "   QUESTION_TABLE   "("  
                QUESTION_ID_COLUMN   " INTEGER PRIMARY KEY,"  
                QUESTION_TEXT_COLUMN   " TEXT"  
                ");");
        db.execSQL("CREATE TABLE IF NOT EXISTS "   ANSWER_TABLE   "("  
                ANSWER_ID_COLUMN   " INTEGER PRIMARY KEY,"  
                ANSWER_TEXT_COLUMN   " TEXT,"  
                ANSWER_QUESTION_MAP_COLUMN   " INTEGER REFERENCES "   QUESTION_TABLE   "("   QUESTION_ID_COLUMN   ") ON DELETE CASCADE ON UPDATE CASCADE,"  
                ANSWER_CORRECT_COLUMN   " INTEGER DEFAULT 0 /* false */"  
                ");");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }

    // Fully comprehensive Question insert
    public long insertQuestion(Long questionId, String questionText) {
        init_db_AsWriteableDatabase();
        long rv = -2;
        ContentValues cv = new ContentValues();
        if (questionId != null && questionId > 0) {
            cv.put(QUESTION_ID_COLUMN,questionId);
        }
        if (questionText != null && questionText.length() > 0) {
            cv.put(QUESTION_TEXT_COLUMN,questionText);
        }
        if (cv.size() > 0) {
            rv = db.insert(QUESTION_TABLE,null,cv);
        }
        return rv;
    }

    // Concise Question insert
    public long insertQuestion(String questionText) {
        return insertQuestion(null,questionText);
    }

    // Fully comprehensive Answer insert
    public long insertAnswer(Long answerId, long questionMap, String answerText, boolean correct) {
        init_db_AsWriteableDatabase();
        long rv = -2;
        ContentValues cv = new ContentValues();
        if (answerId != null && answerId > 0) {
            cv.put(ANSWER_ID_COLUMN,answerId);
        }
        if (answerText != null && answerText.length() > 0) {
            cv.put(ANSWER_CORRECT_COLUMN,correct);
            cv.put(ANSWER_TEXT_COLUMN,answerText);
            cv.put(ANSWER_QUESTION_MAP_COLUMN,questionMap);
            rv = db.insert(ANSWER_TABLE,null,cv);
        }
        return rv;
    }

    // long concise Answer insert
    public long insertAnswer(long questionMap, String answerText, boolean correct) {
        return insertAnswer(null,questionMap,answerText,correct);
    }
    public long insertAnswer(long questionMap, String answerText) {
        return insertAnswer(questionMap,answerText,false);
    }
    // short concise Answer insert
    private void init_db_AsWriteableDatabase() {
        if (db == null) {
            db = this.getWritableDatabase();
        }
    }


    @SuppressLint("Range")
    public QuestionPOJO getQuestionById(long questionId) {
        QuestionPOJO rv = null;
        init_db_AsWriteableDatabase();
        Cursor csr = db.query(QUESTION_TABLE,null,QUESTION_ID_COLUMN "=?",new String[]{String.valueOf(questionId)},null,null,null);
        if (csr.moveToNext()) {
            rv = new QuestionPOJO(csr.getLong(csr.getColumnIndex(QUESTION_ID_COLUMN)),csr.getString(csr.getColumnIndex(QUESTION_TEXT_COLUMN)));
        }
        csr.close();
        return rv;
    }

    @SuppressLint("Range")
    public List<AnswerPOJO> getAnswersForQuestion(long questionId, boolean onlyCorrect) {
        init_db_AsWriteableDatabase();
        ArrayList<AnswerPOJO> rv = new ArrayList<>();
        StringBuilder whereClause = new StringBuilder();
        if (onlyCorrect) {
            whereClause.append(ANSWER_CORRECT_COLUMN);
        }
        Cursor csr = db.query(ANSWER_TABLE,null,whereClause.toString(),null,null,null,null);
        while (csr.moveToNext()) {
            rv.add(
                    new AnswerPOJO(
                            csr.getLong(csr.getColumnIndex(ANSWER_ID_COLUMN)),
                            questionId,
                            csr.getString(csr.getColumnIndex(ANSWER_TEXT_COLUMN)),
                            csr.getInt(csr.getColumnIndex(ANSWER_CORRECT_COLUMN)) > 0
                    )
            );
        }
        csr.close();
        return rv;
    }
}

Finally to put it all together and activity that has a layout for 4 radio buttons along with the associated answer as a TextView.

So the layout is:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!">
    </TextView>

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

        <RadioButton
            android:id="@ id/answer1_radioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            tools:ignore="DuplicateSpeakableTextCheck"></RadioButton>
        <TextView
            android:id="@ id/answer1_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TextView>
        <RadioButton
            android:id="@ id/answer2_radioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </RadioButton>
        <TextView
            android:id="@ id/answer2_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TextView>
        <RadioButton
            android:id="@ id/answer3_radioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </RadioButton>
        <TextView
            android:id="@ id/answer3_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TextView>

        <RadioButton
            android:id="@ id/answer4_radioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </RadioButton>
        <TextView
            android:id="@ id/answer4_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content">
        </TextView>
    </RadioGroup>

</LinearLayout>
  • simple enough to show how hiding the buttons depending upon the number of answers (or a limit according to the number of Buttons/Textviews)

And the activity to demonstrate:-

public class MainActivity extends AppCompatActivity {
    DatabaseHelper dbHelper;
    RadioButton[] radiobuttons = new RadioButton[4];
    TextView[] answerTexts = new TextView[4];
    QuestionWithAnswersPOJO currentQuestionWithAnswers;

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

        /*
            prepare Radion Buttons and associated TextViews
         */
        radiobuttons[0] = this.findViewById(R.id.answer1_radioButton);
        radiobuttons[1] = this.findViewById(R.id.answer2_radioButton);
        radiobuttons[2] = this.findViewById(R.id.answer3_radioButton);
        radiobuttons[3] = this.findViewById(R.id.answer4_radioButton);
        answerTexts[0] = this.findViewById(R.id.answer1_textview);
        answerTexts[1] = this.findViewById(R.id.answer2_textview);
        answerTexts[2] = this.findViewById(R.id.answer3_textview);
        answerTexts[3] = this.findViewById(R.id.answer4_textview);

        /*
            Prepare to use Database
         */
        dbHelper = DatabaseHelper.getInstance(this,true);
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        /* Clear any existing data for consistent results */
        db.delete(DatabaseHelper.ANSWER_TABLE,null,null);
        db.delete(DatabaseHelper.QUESTION_TABLE,null,null);
        /* Add some demo data  1 question with 5 answers (comment out to reduce number of answers)*/
        long q1id = dbHelper.insertQuestion("What is 1   1");
        dbHelper.insertAnswer(q1id,"It is 1");
        dbHelper.insertAnswer(q1id,"it is 2", true);
        dbHelper.insertAnswer(q1id,"It is 3");
        dbHelper.insertAnswer(q1id,"It is 4");
        dbHelper.insertAnswer(q1id,"It is something Else"); // will be ignored because only 4 radio buttons

        /* Get the question with the answers, however many ot has */
        currentQuestionWithAnswers = new QuestionWithAnswersPOJO(dbHelper.getQuestionById(q1id),dbHelper.getAnswersForQuestion(q1id,false));
        /* setup (refresh) the radio buttons and textviews */
        getAndSetRadioButtons(currentQuestionWithAnswers);
    }

    /*
        Does as it says
     */
    private void getAndSetRadioButtons(QuestionWithAnswersPOJO qwa) {
        // Clear All

        for (int i=0;i < radiobuttons.length; i  ) {
            radiobuttons[i].setVisibility(View.GONE);
            answerTexts[i].setText("");
            answerTexts[i].setVisibility(View.GONE);
        }
        /* show only the least of answers/radio buttons */
        int numberToShow = radiobuttons.length;
        if (qwa.answers.size() < radiobuttons.length) {
            numberToShow = qwa.answers.size();
        }
        int i = 0;
        for(AnswerPOJO a: qwa.answers) {
            if (i < numberToShow) {
                radiobuttons[i].setVisibility(View.VISIBLE);
                answerTexts[i].setVisibility(View.VISIBLE);
                answerTexts[i  ].setText(a.answerText);
            } else {
                /* nothing more to do so early break out of the loop */
                break;
            }
        }
    }
}

Results

Result 1 - run with the 5 answers (see comments re 5th answer)

enter image description here

Result 2 - All bar 1 answer comment out so the question has just the 1 answer

The code used:-

    long q1id = dbHelper.insertQuestion("What is 1   1");
    dbHelper.insertAnswer(q1id,"It is 1");
    //dbHelper.insertAnswer(q1id,"it is 2", true);
    //dbHelper.insertAnswer(q1id,"It is 3");
    //dbHelper.insertAnswer(q1id,"It is 4");
    //dbHelper.insertAnswer(q1id,"It is something Else"); // will be ignored because only 4 radio buttons

The display :-

enter image description here

Result 3 - first and 5th answers only inserted

enter image description here

and so on.

  •  Tags:  
  • Related