0
0
Android-kotlinHow-ToBeginner ยท 4 min read

How to Use ViewModel in Android: Simple Guide

In Android, use ViewModel to store and manage UI-related data in a lifecycle-aware way. Create a ViewModel class, then get its instance in your Activity or Fragment using ViewModelProvider to survive configuration changes like screen rotations.
๐Ÿ“

Syntax

The basic syntax involves creating a ViewModel class that extends ViewModel from Android Jetpack. Then, in your Activity or Fragment, you obtain an instance of this ViewModel using ViewModelProvider.

  • ViewModel class: Holds UI data and logic.
  • ViewModelProvider: Creates or retrieves the ViewModel instance tied to the lifecycle.
kotlin
class MyViewModel : ViewModel() {
  var counter = 0
}

// In Activity or Fragment
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
๐Ÿ’ป

Example

This example shows a simple counter app where the count value is stored in a ViewModel. The count survives screen rotations without resetting.

kotlin
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider

class CounterViewModel : ViewModel() {
  var count = 0
}

class MainActivity : AppCompatActivity() {
  private lateinit var viewModel: CounterViewModel

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

    viewModel = ViewModelProvider(this).get(CounterViewModel::class.java)

    val countText: TextView = findViewById(R.id.countText)
    val incrementButton: Button = findViewById(R.id.incrementButton)

    countText.text = viewModel.count.toString()

    incrementButton.setOnClickListener {
      viewModel.count++
      countText.text = viewModel.count.toString()
    }
  }
}
Output
A screen with a number starting at 0 and a button. Pressing the button increases the number. Rotating the device keeps the number unchanged.
โš ๏ธ

Common Pitfalls

Common mistakes when using ViewModel include:

  • Trying to pass Context or View objects into ViewModel, which can cause memory leaks.
  • Not using ViewModelProvider and creating ViewModel instances manually, losing lifecycle benefits.
  • Expecting ViewModel to survive process death; it only survives configuration changes.
kotlin
/* Wrong: Passing Context to ViewModel (causes leaks) */
class BadViewModel(val context: Context) : ViewModel() {}

/* Right: Keep ViewModel free of Context */
class GoodViewModel : ViewModel() {}
๐Ÿ“Š

Quick Reference

Remember these key points when using ViewModel:

  • Use ViewModelProvider(this) in Activity or ViewModelProvider(this) in Fragment to get ViewModel.
  • Keep UI data in ViewModel to survive configuration changes.
  • Do not store Context, View, or Activity references in ViewModel.
  • Use LiveData or StateFlow inside ViewModel for reactive UI updates.
โœ…

Key Takeaways

Use ViewModel to hold UI data that survives configuration changes like screen rotations.
Always get ViewModel instances via ViewModelProvider tied to lifecycle owners.
Avoid storing Context or View references inside ViewModel to prevent memory leaks.
ViewModel does not survive app process death; use saved state or persistence for that.
Combine ViewModel with LiveData or StateFlow for reactive UI updates.