I'm following Google Android Developer codelabs on ViewModel and State. There's a codelab to port an app called Dessert Clicker to ViewModel.
My attempt can be found here:
https://github.com/alghe-global/Kotlin/tree/viewmodel/AndroidBasicsCourse%2FDessertClicker
Unfortunately, the app crashes on startup.
onCreate() is not logged (Logcat is empty), and, placing a breakpoint on super.onCreate(...) in MainActivity won't trigger it leading me to suspect there's a fundamental problem in the way the APK is set-up.
The codelab does provide a solution, however I'm trying to learn how to debug and deal with these kind of issues so if they arise in the future I know what to do.
Any hints are appreciated.
Solution
Looking at Logcat, I realized that the device selected was wrong (my phone was selected instead of the AVD I was using to debug).
Once the correct device was set, I could see the stacktrace in the log:
2024-01-11 11:11:11.119 12385-12385 AndroidRuntime com.example.dessertclicker E FATAL EXCEPTION: main
Process: com.example.dessertclicker, PID: 12385
android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:234)
at android.content.res.Resources.getValue(Resources.java:1439)
at androidx.compose.ui.res.PainterResources_androidKt.painterResource(PainterResources.android.kt:61)
at com.example.dessertclicker.MainActivityKt.DessertClickerScreen(MainActivity.kt:230)
...
This pointed to a resource I was using in the wrong way (UiState instead of ViewModel).
This was resolved with:
diff --git a/AndroidBasicsCourse/DessertClicker/app/src/main/java/com/example/dessertclicker/MainActivity.kt b/AndroidBasicsCourse/DessertClicker/app/src/main/java/com/example/dessertclicker/MainActivity.kt
index 6dffdf0..a9599ee 100644
--- a/AndroidBasicsCourse/DessertClicker/app/src/main/java/com/example/dessertclicker/MainActivity.kt
+++ b/AndroidBasicsCourse/DessertClicker/app/src/main/java/com/example/dessertclicker/MainActivity.kt
@@ -164,7 +164,7 @@ private fun DessertClickerApp(
DessertClickerScreen(
revenue = dessertClickerUiState.revenue,
dessertsSold = dessertClickerUiState.dessertsSold,
- dessertImageId = dessertClickerUiState.currentDessertImageId,
+ dessertImageId = dessertClickerViewModel.currentDessertImageId,
onDessertClicked = {
dessertClickerViewModel.updateRevenue()
dessertClickerViewModel.updateDessertsSold()
Thanks to @a_local_nobody for his/her/their help!
I'm trying to learn how to debugthen there's no better post than that