Search code examples
androidkotlinandroid-activityrotationorientation

How to execute code if activity wasn't re-created from orientation rotation?


I am trying to make a quiz like an app. I have a class which is responsible for handling questions. I also have a view model that will hold these questions and other UI elements to assist with UI rotation changes.

My code looks something like this:

override fun onCreate() {
    var questions = quizModel.generateQuestions()
    quizViewModel.questions = questions
}

The thing is, I only want to do this when the activity was not re-created due to a rotation and change in the orientation of the device. This is because my view model will already hold my list of questions, so I don't need to generate another set of questions, just get the questions from the view model.

Is there some IF condition check I can try to do to execute the code above only when the activity wasn't re-created from orientation changes?


Solution

  • Use:

    protected void onCreate (Bundle savedInstanceState)

    https://developer.android.com/reference/android/app/Activity#onCreate(android.os.Bundle)

    if savedInstanceState is null then its the first time you activity is created, if non-null then it is being recreated.