Bird
Raised Fist0
Android Kotlinmobile~20 mins

Saving instance state in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Counter Screen
A simple screen with a button that increases a counter. The counter value should be saved and restored when the screen is recreated, such as during device rotation.
Target UI
---------------------
|   Counter Screen   |
|-------------------|
|                   |
|   Count: 0        |
|                   |
|   [Increase +1]   |
|                   |
---------------------
Display a counter starting at 0
Add a button labeled 'Increase +1' that increments the counter
Save the counter value when the activity is destroyed
Restore the counter value when the activity is recreated
Starter Code
Android Kotlin
package com.example.savingstate

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

class MainActivity : AppCompatActivity() {
    private var count = 0

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

        val countTextView: TextView = findViewById(R.id.countTextView)
        val increaseButton: Button = findViewById(R.id.increaseButton)

        // TODO: Restore count from savedInstanceState if available

        countTextView.text = "Count: $count"

        increaseButton.setOnClickListener {
            count++
            countTextView.text = "Count: $count"
        }
    }

    // TODO: Override onSaveInstanceState to save the count
}
Task 1
Task 2
Solution
Android Kotlin
package com.example.savingstate

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

class MainActivity : AppCompatActivity() {
    private var count = 0

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

        val countTextView: TextView = findViewById(R.id.countTextView)
        val increaseButton: Button = findViewById(R.id.increaseButton)

        if (savedInstanceState != null) {
            count = savedInstanceState.getInt("COUNT_KEY", 0)
        }

        countTextView.text = "Count: $count"

        increaseButton.setOnClickListener {
            count++
            countTextView.text = "Count: $count"
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putInt("COUNT_KEY", count)
    }
}

We save the current count value in onSaveInstanceState by putting it into the Bundle with a key "COUNT_KEY". When the activity is recreated, onCreate receives the savedInstanceState bundle, from which we retrieve the saved count value. This way, the counter value is preserved across configuration changes like screen rotation.

This is a simple and common way to save small pieces of UI state in Android apps.

Final Result
Completed Screen
---------------------
|   Counter Screen   |
|-------------------|
|                   |
|   Count: 3        |
|                   |
|   [Increase +1]   |
|                   |
---------------------
User taps 'Increase +1' button, count increments by 1 and updates on screen
If user rotates device, the count value stays the same and is displayed correctly
Stretch Goal
Add a reset button to set the counter back to zero and update the display
💡 Hint
Add another Button in the layout and set its onClickListener to reset count to 0 and update the TextView

Practice

(1/5)
1. What is the main purpose of onSaveInstanceState in Android Kotlin apps?
easy
A. To initialize UI components when the app starts
B. To permanently store data in a database
C. To save UI data temporarily during events like screen rotation
D. To handle user input events like button clicks

Solution

  1. Step 1: Understand the role of onSaveInstanceState

    This method is called before an activity might be destroyed, such as during screen rotation, to save temporary UI data.
  2. Step 2: Differentiate from other data storage methods

    Permanent storage like databases is not handled here; onSaveInstanceState is for short-term state saving only.
  3. Final Answer:

    To save UI data temporarily during events like screen rotation -> Option C
  4. Quick Check:

    onSaveInstanceState saves temporary UI state [OK]
Hint: Remember: onSaveInstanceState saves temporary UI data [OK]
Common Mistakes:
  • Confusing onSaveInstanceState with permanent storage
  • Thinking it initializes UI components
  • Assuming it handles user input events
2. Which of the following is the correct way to save a string value "username" in onSaveInstanceState?
easy
A. bundle.putString("username", username)
B. outState.putString("username", username)
C. savedInstanceState.putString("username", username)
D. state.putString("username", username)

Solution

  1. Step 1: Identify the correct parameter name in onSaveInstanceState

    The Bundle parameter is named outState in onSaveInstanceState method.
  2. Step 2: Use the correct method to save a string

    Use outState.putString(key, value) to save the string value.
  3. Final Answer:

    outState.putString("username", username) -> Option B
  4. Quick Check:

    Use outState to save data in onSaveInstanceState [OK]
Hint: Use outState.putString() inside onSaveInstanceState [OK]
Common Mistakes:
  • Using savedInstanceState inside onSaveInstanceState
  • Using undefined variable names like bundle or state
  • Confusing parameter names in lifecycle methods
3. Given this code snippet inside an Activity:
override fun onSaveInstanceState(outState: Bundle) {
  super.onSaveInstanceState(outState)
  outState.putInt("score", 10)
}

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  val score = savedInstanceState?.getInt("score") ?: 0
  println(score)
}

What will be printed after a screen rotation?
medium
A. Crash due to NullPointerException
B. 0
C. null
D. 10

Solution

  1. Step 1: Understand saving the score in onSaveInstanceState

    The score 10 is saved in the outState bundle before the activity is destroyed.
  2. Step 2: Restore score in onCreate after rotation

    savedInstanceState contains the saved bundle, so getInt("score") returns 10, not null or 0.
  3. Final Answer:

    10 -> Option D
  4. Quick Check:

    Saved state restores score = 10 after rotation [OK]
Hint: savedInstanceState?.getInt() returns saved value or default [OK]
Common Mistakes:
  • Assuming savedInstanceState is always null
  • Forgetting to call super.onSaveInstanceState
  • Expecting 0 instead of restored value
4. What is wrong with this code snippet for saving instance state?
override fun onSaveInstanceState(outState: Bundle) {
  outState.putInt("count", count)
}

override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  val count = savedInstanceState?.getInt("count") ?: 0
}
medium
A. Missing call to super.onSaveInstanceState in onSaveInstanceState
B. Using wrong key name "count"
C. Not initializing count variable before saving
D. Not checking savedInstanceState for null in onCreate

Solution

  1. Step 1: Check onSaveInstanceState method

    It lacks a call to super.onSaveInstanceState(outState), which is required to save default state.
  2. Step 2: Verify other parts

    Key name "count" is consistent, count variable assumed initialized, and null check is done in onCreate.
  3. Final Answer:

    Missing call to super.onSaveInstanceState in onSaveInstanceState -> Option A
  4. Quick Check:

    Always call super.onSaveInstanceState [OK]
Hint: Always call super.onSaveInstanceState in override [OK]
Common Mistakes:
  • Forgetting super call in onSaveInstanceState
  • Using inconsistent keys for saving/restoring
  • Ignoring null checks on savedInstanceState
5. You want to save a checkbox state and a user input text during screen rotation. Which approach correctly saves and restores both in an Activity?
hard
A. Save checkbox state and text in onSaveInstanceState using outState.putBoolean and outState.putString, then restore in onCreate using savedInstanceState?.getBoolean and getString
B. Save checkbox state only in onSaveInstanceState, restore text from a global variable
C. Save text in onPause and checkbox state in onStop, restore both in onResume
D. Use SharedPreferences to save checkbox and text, restore in onCreate

Solution

  1. Step 1: Use onSaveInstanceState for temporary UI data

    Checkbox state (boolean) and text (string) should be saved in outState bundle in onSaveInstanceState.
  2. Step 2: Restore saved data in onCreate

    Use savedInstanceState?.getBoolean and getString to restore checkbox and text after rotation.
  3. Final Answer:

    Save checkbox state and text in onSaveInstanceState using outState.putBoolean and outState.putString, then restore in onCreate using savedInstanceState?.getBoolean and getString -> Option A
  4. Quick Check:

    Use onSaveInstanceState and savedInstanceState for UI state [OK]
Hint: Save UI data in onSaveInstanceState, restore in onCreate [OK]
Common Mistakes:
  • Using global variables that reset on rotation
  • Saving data in lifecycle methods not meant for state
  • Using persistent storage for temporary UI state
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard