I am new to Android. I create sign-in and sign-up functionality. But I want to store the data of the user,(before going to the signing screen) when the user is signing up in the FireBase FireStore (based on the current user id). I have the user id, but I don't know the way to do it. The code is attached below. I am glad, If someone could help.
package com.example.firebase
import android.content.Intent
import android.os.Binder
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import com.example.firebase.databinding.ActivitySignUpBinding
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.DocumentReference
import com.google.firebase.firestore.FirebaseFirestore
class Sign_Up_Activity : AppCompatActivity() {
private lateinit var binding: ActivitySignUpBinding
private lateinit var firebaseAuth: FirebaseAuth
private lateinit var firebasefirestore: FirebaseFirestore
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignUpBinding.inflate(layoutInflater)
setContentView(binding.root)
firebaseAuth = FirebaseAuth.getInstance()
firebasefirestore = FirebaseFirestore.getInstance()
binding.signUpButton.setOnClickListener {
val email = binding.emailEt.text.toString()
val password = binding.passET.text.toString()
val confirmPass = binding.confirmPassEt.text.toString()
if (email.isNotEmpty() && password.isNotEmpty() && confirmPass.isNotEmpty()) {
if (password.equals(confirmPass)) {
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (it.isSuccessful) {
val userid:String= firebaseAuth.currentUser!!.uid
firebasefirestore.collection("user").document(userid).get()
Log.d("User id",userid)
val intent = Intent(this, Sign_In_Activity::class.java)
startActivity(intent)
} else {
Toast.makeText(this, it.exception.toString(),
Toast.LENGTH_SHORT)
.show()
}
}
} else {
Toast.makeText(this, "Password is not matching",
Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Empty Fields are not Allowed",
Toast.LENGTH_SHORT).show()
}
}
}
}
CodePudding user response:
When you're using the following line of code:
firebasefirestore.collection("user").document(userid).get()
You aren't setting the user to Firestore, you're only reading it. If you want to add the data to the database, you have to use set() like in the following lines of code:
val db = Firebase.firestore
val user = mapOf("email" to firebaseAuth.currentUser!!.email)
val userRef = db.collection("user")
userRef.document(userid).set(user)
.addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully written!") }
.addOnFailureListener { e -> Log.w(TAG, "Error writing document", e) }
If you're interested in implementing Firebase authentication with Google, then please check the following article:
If you want by chance to implement the anonymous authentication, then please check: