1

I want it to log in with google to keep users favorite words in my app. When the user exits the application, the user comes back to the login page with google. And all the user's favorite words are deleted. how can I solve this problem Below I show the deleted parts?

class SignInActivity : AppCompatActivity() {

    companion object {
        private const val RC_SIGN_IN = 120
    }

    private lateinit var mAuth: FirebaseAuth
    private lateinit var googleSignInClient: GoogleSignInClient

    private lateinit var database: DatabaseReference


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sign_in)

        val sign_in_btn : Button = findViewById(R.id.sign_in_btn)

        // Configure Google Sign In
        val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build()
        googleSignInClient = GoogleSignIn.getClient(this, gso)


        database = Firebase.database.reference

        //Firebase Auth instance
        mAuth = FirebaseAuth.getInstance()

        sign_in_btn.setOnClickListener {
            signIn()
        }
    }

    private fun writeNewUser(userId: String, name: String, email: String) {
        val user = Users(userId, name, email)

        database.child("users").child(userId).setValue(user)
    }

    private fun signIn() {
        val signInIntent = googleSignInClient.signInIntent
        startActivityForResult(signInIntent, RC_SIGN_IN)    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            val task = GoogleSignIn.getSignedInAccountFromIntent(data)
            val exception = task.exception

            if(task.isSuccessful){
                try {
                    // Google Sign In was successful, authenticate with Firebase
                    val account = task.getResult(ApiException::class.java)!!
                    Log.d(ContentValues.TAG, "firebaseAuthWithGoogle:" + account.id)
                    firebaseAuthWithGoogle(account.idToken!!)
                } catch (e: ApiException) {
                    // Google Sign In failed, update UI appropriately
                    Log.w(ContentValues.TAG, "Google sign in failed", e)
                }
            }else{
                Log.w(ContentValues.TAG, exception.toString())
            }

        }
    }
    private fun firebaseAuthWithGoogle(idToken: String) {
        val credential = GoogleAuthProvider.getCredential(idToken, null)
        mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this) { task ->
                if (task.isSuccessful) {

                    val user = mAuth.currentUser
                    writeNewUser(user?.uid.toString(), user?.displayName.toString(),
                        user?.email.toString()
                    )
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(ContentValues.TAG, "signInWithCredential:success")

                    val intent = Intent(this, DashboardActivity::class.java)
                    startActivity(intent)
                    finish()
                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(ContentValues.TAG, "signInWithCredential:failure", task.exception) }
            }
    }
}

And my SignOut function

     sign_out_btn.setOnClickListener {
            mAuth.signOut()
            val intent = Intent(this,SignInActivity::class.java)
            startActivity(intent)
            finish()
        }

enter image description here

John Conde
  • 217,595
  • 99
  • 455
  • 496
a.snss
  • 143
  • 3
  • 10

1 Answers1

0

You are always getting everything wiped out because when you perform a successful Firebase authentication with Google you always call writeNewUser() method, which actually performs a write operation in the database using the following line of code:

database.child("users").child(userId).setValue(user)

So this actually means that you always write the user object on the existing one. Surprising, this is not what you want. To solve this, you need to check if the user already exists in the database before performing a new write operation. So please check my answer from the following post:

So you only need to write user data if it doesn't already exist.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193