0
0
Android Kotlinmobile~5 mins

ViewModel creation in Android Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a ViewModel in Android development?
A ViewModel is a class that holds UI data and survives configuration changes like screen rotations. It helps keep data separate from UI controllers like Activities or Fragments.
Click to reveal answer
beginner
How do you create a simple ViewModel class in Kotlin?
You create a class that extends <code>ViewModel</code>. For example:<br><pre>class MyViewModel : ViewModel() { }</pre>
Click to reveal answer
beginner
Why should UI data be stored in a ViewModel instead of an Activity?
Because ViewModel survives configuration changes, it prevents data loss when the screen rotates. Activities get destroyed and recreated, losing their data.
Click to reveal answer
intermediate
How do you obtain a ViewModel instance inside an Activity?
Use the ViewModelProvider like this:<br>
val model = ViewModelProvider(this).get(MyViewModel::class.java)
Click to reveal answer
intermediate
What is the benefit of using LiveData inside a ViewModel?
LiveData holds data that UI can observe. It updates the UI automatically when data changes, and respects lifecycle to avoid crashes.
Click to reveal answer
What does a ViewModel help with in Android apps?
AManaging network connections
BDrawing UI elements on screen
CKeeping UI data during screen rotations
DHandling user input events
Which class should your ViewModel extend?
AActivity
BViewModel
CFragment
DApplication
How do you get a ViewModel instance in an Activity?
Anew ViewModel()
BfindViewById()
CgetSystemService()
DViewModelProvider(this).get()
What happens to data stored in an Activity when the screen rotates?
AIt is lost unless saved
BIt is preserved automatically
CIt is sent to the server
DIt is cached permanently
Why use LiveData inside a ViewModel?
ATo observe data changes safely
BTo draw graphics
CTo handle user clicks
DTo store files
Explain how to create and use a ViewModel in an Android app.
Think about separating UI data from Activity lifecycle.
You got /4 concepts.
    Describe why ViewModel is important for handling screen rotations.
    Imagine what happens when you turn your phone sideways.
    You got /4 concepts.