Implementing the Lifecycle of an Android Application: Preserving State during Changes in Screen Orientation.

Table of contents

Preview

During app development, there may be instances where we desire to rotate the screen to achieve a better view of the layout. However, a problem arises where the data or changes made are reset to their original state as if the app was launched for the first time. This occurs because the activity is rerun entirely. How can we prevent this issue? Let's examine it further.

Before delving into the coding, it may be helpful to first download the source code. Here's the link:

Activity Lifecycle of Android Development

However, if you prefer to code along with me, that's perfectly fine as well. To begin, you'll need to create a new project and modify the code in the activity_main.xml file as follows:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:breakStrategy="balanced"
        android:textSize="32dp"
        android:text="0"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:text="Add Number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

And then your MainActivity.kt like this :

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity() {

    private lateinit var textView: TextView

    private lateinit var button: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView = findViewById(R.id.textView)
        button = findViewById(R.id.button)

        var countingNumber = 0

        button.setOnClickListener {
            countingNumber++
            textView.setText(countingNumber.toString())
        }
    }
}

Perhaps you're wondering about the purpose of the code. Please be patient. Before we apply the solution, I want you to have a good understanding of the project.

Let's run the code. You can try clicking the button and observe the number increasing. You should see a view similar to this:

What occurs when we rotate the application?

The incremented value of the number will be restored to its initial state when we run the application again after rotating it.

So, how can we resolve this issue? We can utilize the 'saved instance state' feature.

Here are the steps:

1. Firstly, we need to create a string within the companion object to store and retrieve the data.

companion object{
        const val COUNTER_STATE_KEY = "counterNumber"
    }

2. We have to add the "onSaveInstanceState" method

override fun onSaveInstanceState(outState: Bundle) {
        outState.putInt(COUNTER_STATE_KEY, countingNumber)

        super.onSaveInstanceState(outState)
    }

3. After creating the string within the companion object, the next step is to configure the TextView value within the onRestoreInstanceState method.

override fun onRestoreInstanceState(
        savedInstanceState: Bundle?,
        persistentState: PersistableBundle?
    ) {
        textView.setText(savedInstanceState?.getInt(COUNTER_STATE_KEY).toString())
        super.onRestoreInstanceState(savedInstanceState, persistentState)
    }

4. Lastly, don't forget to set the counterNumber value within the onCreate() method.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)



        if (savedInstanceState != null) {
            countingNumber =  savedInstanceState.getInt(COUNTER_STATE_KEY)
        }
        textView = findViewById(R.id.textView)
        button = findViewById(R.id.button)



        button.setOnClickListener {
            countingNumber++
            textView.setText(countingNumber.toString())
        }
    }

No you can run the app and the current value will not restore when you rotate the rotation of app.