How to add snackbar when user already exists in jetpack compose android

81 Views Asked by At

I want to show the user snackbar when user already exists in firebase. How can I add a snackbar notification when .addOnFailureListener or user already exists? I have conceptual knowledge gap so explain it briefly.

 package com.example.bettehomes.data.signup
    
    import android.util.Log
    import androidx.compose.runtime.mutableStateOf
    import androidx.lifecycle.ViewModel
    import com.google.firebase.auth.FirebaseAuth
    import com.google.firebase.auth.FirebaseAuth.AuthStateListener
    import com.example.bettehomes.data.RegistrationUIState
    import com.example.bettehomes.data.rules.Validator
    import com.example.bettehomes.navigation.BetteHomesAppRouter
    import com.example.bettehomes.navigation.Screens
    
    
    class SignupViewModel : ViewModel() {
    
        private val TAG = SignupViewModel::class.simpleName
    
    
        var registrationUIState = mutableStateOf(RegistrationUIState())
    
        var allValidationsPassed = mutableStateOf(false)
    
        var signUpInProgress = mutableStateOf(false)
    
        fun onEvent(event: SignupUIEvent) {
            when (event) {
                is SignupUIEvent.FirstNameChanged -> {
                    registrationUIState.value = registrationUIState.value.copy(
                        firstName = event.firstName
                    )
                    printState()
                }
    
                is SignupUIEvent.LastNameChanged -> {
                    registrationUIState.value = registrationUIState.value.copy(
                        lastName = event.lastName
                    )
                    printState()
                }
    
                is SignupUIEvent.EmailChanged -> {
                    registrationUIState.value = registrationUIState.value.copy(
                        email = event.email
                    )
                    printState()
    
                }
    
    
                is SignupUIEvent.PasswordChanged -> {
                    registrationUIState.value = registrationUIState.value.copy(
                        password = event.password
                    )
                    printState()
    
                }
    
                is SignupUIEvent.RegisterButtonClicked -> {
                    signUp()
                }
    
                is SignupUIEvent.PrivacyPolicyCheckBoxClicked -> {
                    registrationUIState.value = registrationUIState.value.copy(
                        privacyPolicyAccepted = event.status
                    )
                }
            }
            validateDataWithRules()
        }
    
    
        private fun signUp() {
            Log.d(TAG, "Inside_signUp")
            printState()
            createUserInFirebase(
                email = registrationUIState.value.email,
                password = registrationUIState.value.password
            )
        }
    
        private fun validateDataWithRules() {
            val fNameResult = Validator.validateFirstName(
                fName = registrationUIState.value.firstName
            )
    
            val lNameResult = Validator.validateLastName(
                lName = registrationUIState.value.lastName
            )
    
            val emailResult = Validator.validateEmail(
                email = registrationUIState.value.email
            )
    
    
            val passwordResult = Validator.validatePassword(
                password = registrationUIState.value.password
            )
    
            val privacyPolicyResult = Validator.validatePrivacyPolicyAcceptance(
                statusValue = registrationUIState.value.privacyPolicyAccepted
            )
    
    
            Log.d(TAG, "Inside_validateDataWithRules")
            Log.d(TAG, "fNameResult= $fNameResult")
            Log.d(TAG, "lNameResult= $lNameResult")
            Log.d(TAG, "emailResult= $emailResult")
            Log.d(TAG, "passwordResult= $passwordResult")
            Log.d(TAG, "privacyPolicyResult= $privacyPolicyResult")
    
            registrationUIState.value = registrationUIState.value.copy(
                firstNameError = fNameResult.status,
                lastNameError = lNameResult.status,
                emailError = emailResult.status,
                passwordError = passwordResult.status,
                privacyPolicyError = privacyPolicyResult.status
            )
    
    
            allValidationsPassed.value = fNameResult.status && lNameResult.status &&
                    emailResult.status && passwordResult.status && privacyPolicyResult.status
    
        }
    
    
        private fun printState() {
            Log.d(TAG, "Inside_printState")
            Log.d(TAG, registrationUIState.value.toString())
        }
    
    
        private fun createUserInFirebase(email: String, password: String) {
    
            signUpInProgress.value = true
    
            FirebaseAuth
                .getInstance()
                .createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener {
                    Log.d(TAG, "Inside_OnCompleteListener")
                    Log.d(TAG, " isSuccessful = ${it.isSuccessful}")
    
    
                    signUpInProgress.value = false
                    if (it.isSuccessful) {
                        BetteHomesAppRouter.navigateTo(Screens.HomeScreen)
                    }
                }
                .addOnFailureListener {
                    Log.d(TAG, "Inside_OnFailureListener")
                    Log.d(TAG, "Exception= ${it.message}")
                    Log.d(TAG, "Exception= ${it.localizedMessage}")
                    scope.launch {
                        snackbarHostState.showSnackbar("Snackbar")
                    }
                }
        }
    
    
    }
1

There are 1 best solutions below

0
On

This is how I added the snackbar.

  1. Create a Scaffold to contain the contents.

  2. add val scope = rememberCoroutineScope() and val snackbarHostState = remember { snackbarHostState()}

  3. In the SignupViewModels.kt create a var userExists = MutableStateOf("false") and mutate this to in .addOnFailureListener userExists.value = true.

  4. Then in ButtonComponent of SignUpScreen.kt

    ButtonComponent( value = stringResource(id = R.string.register), onButtonClicked = { signupViewModel.onEvent(SignupUIEvent.RegisterButtonClicked) if (signupViewModel.userExists.value){ scope.launch { snackbarHostState.showSnackbar("The Email address is already in use!") } }}, isEnabled = signupViewModel.allValidationsPassed.value )