I'm new to android studio with kotlin.
I want to make multiple choice quiz app, and I use data class and object constant to supply problem. If users choose correct choice, private var mCurrentPosition(Int) get plus 1 and setQuestion() work to change the problem, choices, and correctChoice.
To prevent the progress from being reset after the app is closed, I thought it would be okay if the int of mCurrentPosition was stored, so I use onSaveIntanceState. But progress is initialized after the app is closed...
class QuizActivity : AppCompatActivity() {
private var mCurrentPosition: Int = 1
private var mQuestion300List: ArrayList<Question300>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if(savedInstanceState != null) {
with(savedInstanceState) {
mCurrentPosition = getInt(STATE_SCORE)
}
} else {
mCurrentPosition = 1
}
setContentView(R.layout.activity_quiz)
val questionList = Constant.getQuestions()
Log.i("Question Size", "${questionList.size}")
mQuestion300List = Constant.getQuestions()
setQuestion()
tv_choice1.setOnClickListener {
if (tv_correctChoice.text.toString() == "1") {
mCurrentPosition ++
setQuestion()
} else {
tv_choice1.setBackgroundResource(R.drawable.shape_wrongchoice)
}
}
tv_choice2.setOnClickListener {
if (tv_correctChoice.text.toString() == "2") {
mCurrentPosition ++
setQuestion()
} else {
tv_choice2.setBackgroundResource(R.drawable.shape_wrongchoice)
}
}
tv_choice3.setOnClickListener {
if (tv_correctChoice.text.toString() == "3") {
mCurrentPosition ++
setQuestion()
} else {
tv_choice3.setBackgroundResource(R.drawable.shape_wrongchoice)
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
outState?.run {
putInt(STATE_SCORE, mCurrentPosition)
}
super.onSaveInstanceState(outState)
}
companion object {
val STATE_SCORE = "score"
}
private fun setQuestion() {
val question300 = mQuestion300List!![mCurrentPosition-1]
tv_question.text = question300!!.question
tv_choice1.text = question300.choice1
tv_choice2.text = question300.choice2
tv_choice3.text = question300.choice3
tv_correctChoice.text = question300.correctChoice
tv_now.setText("${mCurrentPosition}")
tv_choice1.setBackgroundResource(R.drawable.shape_problem)
tv_choice2.setBackgroundResource(R.drawable.shape_problem)
tv_choice3.setBackgroundResource(R.drawable.shape_problem)
}
}
here is my app code. plz give me help :) thank you