Skip to content

Commit

Permalink
- Move ImageInfo and Constants file out of data folder
Browse files Browse the repository at this point in the history
- Create local variable for showFavoriteDialog
- Pass shared preference in view mode factory
  • Loading branch information
lehcar09 committed Sep 3, 2024
1 parent 0d97aab commit 1182dba
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,10 @@ import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.preference.PreferenceManager
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.analytics.R
import com.google.firebase.quickstart.analytics.kotlin.data.Constants
import com.google.firebase.quickstart.analytics.kotlin.data.ImageInfo
import com.google.firebase.quickstart.analytics.kotlin.ui.theme.FirebaseAnalyticsTheme
import kotlinx.coroutines.launch

Expand All @@ -87,17 +88,19 @@ class ComposeMainActivity : ComponentActivity() {

@Composable
fun MainAppView(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
analyticsViewModel: FirebaseAnalyticsViewModel = viewModel(factory = FirebaseAnalyticsViewModel.Factory)
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current
) {
val context = LocalContext.current
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
val analyticsViewModel: FirebaseAnalyticsViewModel = viewModel(
factory = FirebaseAnalyticsViewModel.Factory(Firebase.analytics, sharedPreferences)
)
val snackbarHostState = remember { SnackbarHostState() }

DisposableEffect(lifecycleOwner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_CREATE) {
recordImageView(analyticsViewModel, context)

} else if (event == Lifecycle.Event.ON_RESUME) {
recordScreenView(analyticsViewModel, context)
}
Expand All @@ -112,11 +115,8 @@ fun MainAppView(

// Load favorite food on initial composition
LaunchedEffect(Unit) {
analyticsViewModel.getUserFavoriteFood(context)
if(analyticsViewModel.userFavoriteFood.value == null)
analyticsViewModel.showFavoriteFoodDialog.value = true
else
analyticsViewModel.setUserFavoriteFood(context, analyticsViewModel.userFavoriteFood.value)
}

Scaffold(
Expand Down Expand Up @@ -244,7 +244,6 @@ fun FavoriteFoodDialog(
snackbarHostState: SnackbarHostState
) {
if (analyticsViewModel.showFavoriteFoodDialog.value) {
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
val choices = stringArrayResource(id = R.array.food_items)
var selectedItem by remember { mutableIntStateOf(0) }
Expand Down Expand Up @@ -272,9 +271,8 @@ fun FavoriteFoodDialog(
},
confirmButton = {
Button(onClick = {
analyticsViewModel.showFavoriteFoodDialog.value = false
val selectedFood = choices[selectedItem]
analyticsViewModel.setUserFavoriteFood(context, selectedFood)
analyticsViewModel.setUserFavoriteFood(selectedFood)
coroutineScope.launch {
snackbarHostState.showSnackbar("Favorite Food selected: $selectedFood")
}
Expand Down Expand Up @@ -316,6 +314,6 @@ private fun recordImageView(analyticsViewModel: FirebaseAnalyticsViewModel, cont
@Composable
fun MainAppPreview() {
FirebaseAnalyticsTheme {
MainAppView(viewModel(factory = FirebaseAnalyticsViewModel.Factory))
MainAppView()
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.google.firebase.quickstart.analytics.kotlin.data
package com.google.firebase.quickstart.analytics.kotlin

import com.google.firebase.quickstart.analytics.R

Expand Down
Original file line number Diff line number Diff line change
@@ -1,47 +1,56 @@
package com.google.firebase.quickstart.analytics.kotlin

import android.content.Context
import android.content.SharedPreferences
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.preference.PreferenceManager
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.analytics.kotlin.data.Constants

class FirebaseAnalyticsViewModel (
private val firebaseAnalytics: FirebaseAnalytics
private val firebaseAnalytics: FirebaseAnalytics,
private val sharedPreferences: SharedPreferences
): ViewModel() {

val showFavoriteFoodDialog = mutableStateOf(false)

private val _selectedImageIndex = mutableIntStateOf(0)
val selectedImageIndex: MutableState<Int> = _selectedImageIndex

private val _userFavoriteFood = mutableStateOf<String?>(null)
val userFavoriteFood: MutableState<String?> = _userFavoriteFood

private val _showFavoriteFoodDialog = mutableStateOf(false)
val showFavoriteFoodDialog: MutableState<Boolean> = _showFavoriteFoodDialog

init {
getUserFavoriteFood()
if(_userFavoriteFood.value == null) {
_showFavoriteFoodDialog.value = true
} else {
setUserFavoriteFood(_userFavoriteFood.value)
}
}

fun setSelectedImageIndex(index: Int) {
_selectedImageIndex.intValue = index
}

fun setUserFavoriteFood(context: Context, food: String?) {
fun setUserFavoriteFood(food: String?) {
_showFavoriteFoodDialog.value = false
_userFavoriteFood.value = food
PreferenceManager.getDefaultSharedPreferences(context).edit()
sharedPreferences.edit()
.putString(Constants.KEY_FAVORITE_FOOD, food)
.apply()

firebaseAnalytics.setUserProperty("favorite_food", food)
}

fun getUserFavoriteFood(context: Context) {
_userFavoriteFood.value = PreferenceManager.getDefaultSharedPreferences(context)
.getString(Constants.KEY_FAVORITE_FOOD, null)
private fun getUserFavoriteFood() {
_userFavoriteFood.value = sharedPreferences.getString(Constants.KEY_FAVORITE_FOOD, null)
}

fun recordShareEvent(imageTitle: String, text: String) {
Expand Down Expand Up @@ -69,14 +78,16 @@ class FirebaseAnalyticsViewModel (
companion object {
// Used to inject this ViewModel's dependencies
// See also: https://developer.android.com/topic/libraries/architecture/viewmodel/viewmodel-factories
val Factory: ViewModelProvider.Factory = object : ViewModelProvider.Factory {
fun Factory(
firebaseAnalytics: FirebaseAnalytics = Firebase.analytics,
sharedPreferences: SharedPreferences
): ViewModelProvider.Factory = object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(
modelClass: Class<T>,
extras: CreationExtras
): T {
val firebaseAnalytics = Firebase.analytics
return FirebaseAnalyticsViewModel(firebaseAnalytics) as T
return FirebaseAnalyticsViewModel(firebaseAnalytics, sharedPreferences) as T
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.google.firebase.quickstart.analytics.kotlin.data
package com.google.firebase.quickstart.analytics.kotlin

/**
* Pair of resource IDs representing an image and its title.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package com.google.firebase.quickstart.analytics.kotlin

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
Expand All @@ -11,14 +12,15 @@ import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.preference.PreferenceManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.analytics.R
import com.google.firebase.quickstart.analytics.databinding.ActivityMainBinding
import com.google.firebase.quickstart.analytics.kotlin.data.Constants
import com.google.firebase.quickstart.analytics.kotlin.data.ImageInfo
import java.util.Locale

/**
Expand All @@ -40,30 +42,30 @@ class MainActivity : AppCompatActivity() {
private lateinit var imagePagerAdapter: ImagePagerAdapter

private lateinit var context: Context
private lateinit var sharedPrefs: SharedPreferences

// Injects FirebaseAnalytics and app measurement configuration from the factory for centralized management.
// [START declare_analytics]
// [START shared_app_measurement]
private val viewModel: FirebaseAnalyticsViewModel by viewModels { FirebaseAnalyticsViewModel.Factory }
// [END shared_app_measurement]
// [END declare_analytics]
private lateinit var viewModel: FirebaseAnalyticsViewModel

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)

context = applicationContext
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
// [START declare_analytics]
// [START shared_app_measurement]
viewModel = viewModels<FirebaseAnalyticsViewModel> {
FirebaseAnalyticsViewModel.Factory(Firebase.analytics, sharedPrefs)
}.value
// [END shared_app_measurement]
// [END declare_analytics]

// On first app open, ask the user his/her favorite food. Then set this as a user property
// on all subsequent opens.
viewModel.getUserFavoriteFood(context)
if (viewModel.userFavoriteFood.value == null) {
if (viewModel.showFavoriteFoodDialog.value) {
askFavoriteFood()
} else {
// [START user_property]
viewModel.setUserFavoriteFood(context, viewModel.userFavoriteFood.value)
// [END user_property]
}

// Create the adapter that will return a fragment for each image.
Expand Down Expand Up @@ -108,7 +110,7 @@ class MainActivity : AppCompatActivity() {
val food = choices[which]

// [START user_property]
viewModel.setUserFavoriteFood(context, food)
viewModel.setUserFavoriteFood(food)
// [END user_property]
}.create()
ad.show()
Expand Down

0 comments on commit 1182dba

Please sign in to comment.