adding items to MutableList using viewmodel

547 views Asked by At

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)
        //create a function to return the result to MainActivity
        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 another activity, the list is destroyed and nothing is saved in it anymore... how can i keep the mutablelist saved even if i closed the activity?

1

There are 1 answers

0
Shobhith On

If you want the data to be saved even after closing the application and re opening it (Not temporary closing) you can use local storage like Room to save the data... But if you only want to save the data in a session then as Tenfour04 said you can use a activity and multiple fragment and use a single viewmodel pattern to save.....