From 97bc0fafc76840d664de3907d2000cc85fd986cd Mon Sep 17 00:00:00 2001
From: 62160052 <62160052@go.buu.ac.th>
Date: Mon, 19 Sep 2022 01:11:49 +0700
Subject: [PATCH] Update StartFragment to use view model

---
 app/src/main/java/com/example/cupcake/StartFragment.kt    | 8 ++++++++
 .../main/java/com/example/cupcake/model/OrderViewModel.kt | 4 ++++
 2 files changed, 12 insertions(+)

diff --git a/app/src/main/java/com/example/cupcake/StartFragment.kt b/app/src/main/java/com/example/cupcake/StartFragment.kt
index 2bf88c5..81876d9 100644
--- a/app/src/main/java/com/example/cupcake/StartFragment.kt
+++ b/app/src/main/java/com/example/cupcake/StartFragment.kt
@@ -15,12 +15,14 @@
  */
 package com.example.cupcake
 
+import OrderViewModel
 import android.os.Bundle
 import android.view.LayoutInflater
 import android.view.View
 import android.view.ViewGroup
 import android.widget.Toast
 import androidx.fragment.app.Fragment
+import androidx.fragment.app.activityViewModels
 import androidx.navigation.fragment.findNavController
 import com.example.cupcake.databinding.FragmentStartBinding
 
@@ -33,6 +35,7 @@ class StartFragment : Fragment() {
     // This property is non-null between the onCreateView() and onDestroyView() lifecycle callbacks,
     // when the view hierarchy is attached to the fragment.
     private var binding: FragmentStartBinding? = null
+    private val sharedViewModel: OrderViewModel by activityViewModels()
 
     override fun onCreateView(
         inflater: LayoutInflater, container: ViewGroup?,
@@ -58,9 +61,14 @@ class StartFragment : Fragment() {
      * Start an order with the desired quantity of cupcakes and navigate to the next screen.
      */
     fun orderCupcake(quantity: Int) {
+        sharedViewModel.setQuantity(quantity)
+        if (sharedViewModel.hasNoFlavorSet()) {
+            sharedViewModel.setFlavor(getString(R.string.vanilla))
+        }
         findNavController().navigate(R.id.action_startFragment_to_flavorFragment)
     }
 
+
     /**
      * This fragment lifecycle method is called when the view hierarchy associated with the fragment
      * is being removed. As a result, clear out the binding object.
diff --git a/app/src/main/java/com/example/cupcake/model/OrderViewModel.kt b/app/src/main/java/com/example/cupcake/model/OrderViewModel.kt
index 0581a23..afaa9e1 100644
--- a/app/src/main/java/com/example/cupcake/model/OrderViewModel.kt
+++ b/app/src/main/java/com/example/cupcake/model/OrderViewModel.kt
@@ -26,4 +26,8 @@ class OrderViewModel : ViewModel() {
     fun setDate(pickupDate: String) {
         _date.value = pickupDate
     }
+
+    fun hasNoFlavorSet(): Boolean {
+        return _flavor.value.isNullOrEmpty()
+    }
 }
\ No newline at end of file
-- 
GitLab