When developing Android apps with Kotlin in Android Studio, crashes during screen rotation (orientation change) are common especially for beginners. This article will guide you step-by-step to understand the cause, and fix it properly using best practices. We’ll also include complete code examples split by class for clarity.

Why Kotlin Apps Crash on Orientation Change?
Orientation change forces the Android system to destroy and recreate the activity. If your app doesn’t properly handle state restoration, it may crash—often due to:
- Unhandled
nullreferences - Missing
ViewModelusage - Improper use of
Fragment - Large objects in
onSaveInstanceState() - Incorrect lifecycle handling
How to Fix It (Best Practices)
We’ll build a simple counter app that doesn’t crash on rotation. It uses:
ViewModelfor state retention- Proper lifecycle observation
- Kotlin best practices
1. MainActivity.kt
package com.example.rotationfix
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.example.rotationfix.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val counterViewModel: CounterViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnIncrement.setOnClickListener {
counterViewModel.incrementCounter()
}
counterViewModel.counter.observe(this, Observer {
binding.tvCounter.text = it.toString()
})
}
}
2. CounterViewModel.kt
package com.example.rotationfix
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class CounterViewModel : ViewModel() {
private val _counter = MutableLiveData(0)
val counter: LiveData<Int> = _counter
fun incrementCounter() {
_counter.value = (_counter.value ?: 0) + 1
}
}
3. activity_main.xml (in res/layout)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:padding="16dp">
<TextView
android:id="@+id/tvCounter"
android:text="0"
android:textSize="48sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btnIncrement"
android:text="Increment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"/>
</LinearLayout>
Tips to Prevent Orientation Crash
- Use
ViewModelinstead of saving state manually - Avoid heavy operations in
onCreate() - Separate UI logic and business logic
- Use
savedInstanceStateonly for small data (e.g., scroll position)
Further Reading: Android Lifecycle Management Guide