Deb
Deb

Reputation: 59

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.

Upvotes: 0

Views: 489

Answers (1)

Tenfour04
Tenfour04

Reputation: 93789

list.shuffled().take(10) And make your mQuestionsList property type List instead of ArrayList since you don’t need to modify it after retrieval. You should also probably make it lateinit or initialize it at its declaration site so you won’t have to make the type nullable and have to resort to !!, which is generally a code smell. So I would declare it as var mQuestionsList: List<Question> = emptyList() and whenever you want new values do mQuestionsList = Constants.getQuestions().shuffled().take(10).

Upvotes: 1

Related Questions