samedi 18 septembre 2021

How do I pull entries from an ArrayList at random in Kotlin?

This is my first Kotlin project. I am learning as I go and I have reached a roadblock.

I have an ArrayList of questions that I want to pull into that app in a random order. I've tried assigning the .random to the point where the question is assigned (right now it is set to CurrentPosition-1) but that only randomized the question and didn't pull the correct answers along with the questions.

How do I either bundle the answers to the question or is there a better way to get the questions to shuffle in order? I plan on having 50+ questions but only 10 will show each time the test is taken. I don't want the same 10 questions showing each time the user opens the test.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_quiz_questions)

mQuestionsList=Constants.getQuestions()

    setQuestion()

}



private fun setQuestion(){
    val question = mQuestionsList!![mCurrentPosition-1]
    defaultOptionsView()

    if(mCurrentPosition == mQuestionsList!!.size){
        submitBtn.text = "Finish"
    }else{
        submitBtn.text = "Submit"
    }

    progressBar.progress = mCurrentPosition
    tv_progress.text = "$mCurrentPosition" + "/" + progressBar.max

    tv_question.text = question!!.question
    test_image.setImageResource(question.image)

    tvOptionOne.text = question.optionOne
    tvOptionTwo.text = question.optionTwo
    tvOptionThree.text = question.optionThree
    tvOptionFour.text = question.optionFour
}

private fun defaultOptionsView(){
    val options = ArrayList<TextView>()
    options.add(0, tvOptionOne)
    options.add(1, tvOptionTwo)
    options.add(2, tvOptionThree)
    options.add(3, tvOptionFour)

Here is my Array

object Constants{

const val TOTAL_QUESTIONS: String = "total_questions"
const val CORRECT_ANSWERS: String = "correct_answers"


fun getQuestions(): ArrayList<Question>{
    val questionsList = ArrayList<Question>()

    val q1 = Question(
             R.drawable.questionmark,
            1,
            "Who is Regional Manager of\n Dunder Mifflin Scranton?",
            "Michael",
            "Jim",
            "Pam",
            "Dwight",
            1,
    )

I appreciate any help at all. Thank you in advance.




Aucun commentaire:

Enregistrer un commentaire