Question: MutableList in a viewmodel file

I have a mutable list created in a viewmodel file that saves the data

  //questions they cheated on
    var cheatedList = mutableListOf<Int>(6)

I linked the viewmodel file with the file that has functions this way

  private val quizViewModel : QuizViewModel by lazy {
        ViewModelProviders.of(this).get(QuizViewModel::class.java)
    }

it is working fine and i checked it. all i need from it is to save a content of Integers into a mutable list… I use this function to do so

showAnswerButton.setOnClickListener {
        val answerText = when{
            answerIsTrue -> R.string.true_button
            else -> R.string.false_button
        }
        answerTextView.setText(answerText)
        setAnswerShownResult(true)
        cheaterStatus = true

        quizViewModel.cheatedList.add(currentIndex)
        println(quizViewModel.cheatedList)
    }

the good news is, it saves the index into the list… the bad news is once i move back to main activity, the list is destroyed and nothing is saved in it anymore…
how can i keep the mutablelist saved even if i closed the cheat activity?

I’m confused.
Have you scoped QuizViewModel to MainActivity or CheatActivity?
If you’ve scoped it to CheatActivity once the activity is destroyed (which it will be when you press the back button) so too will the ViewModel.

1 Like