I'm currently working on an Android project and I've been stuck with this problem for a few hours now.
I'm trying to connect to my Firestore database. The idea is to store documents with additional info from the users. It's created on-register and then sent to the database.
Here's the code:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success
Log.d("RegistroFirebase", "createUserWithEmail:success")
val user = auth.currentUser
// Create user's database document
writeNewUser(
user!!.uid, user!!.email, binding.signUpName.text.toString(),
binding.signUpSurname.text.toString(), "623623623")
Log.d("Crear documento usuario", "Success?")
reload("main")`
And the function:
private fun writeNewUser(userId: String, email: String?, name: String, surname: String, phone:String) {
val user = User(email, name, surname, phone)
db.child("users").child(userId).setValue(user)
}
Also I have a class for users:
data class User(val email:String? = null, val name:String? = null,
val surname:String? = null, val phone:String? = null) {}
As for the error, I this single line from the logcat.
2021-11-16 13:56:25.826 12534-12665/com.example.senato W/PersistentConnection: pc_0 - Firebase Database connection was forcefully killed by the server. Will not attempt to reconnect. Reason: Firebase error. Please ensure that you spelled the name of your Firebase correctly
Any help would be appreciated. Thank you in advance
CodePudding user response:
You say:
I cannot seem to connect to Firestore database to save user's data
And it makes sense, since when using the following lines of code:
val user = User(email, name, surname, phone)
db.child("users").child(userId).setValue(user)
You are trying to write data to the Realtime Database and not to Cloud Firestore. While both, databases are a part of Firebase services, they are different databases with different mechanisms. To be able to write data to Firestore, please use the following line of code:
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference usersRef = db.collection("users");
usersRef.document(userId).set(user)
You can also attach a listener to the complete operation, to see if something goes wrong.
CodePudding user response:
Similar to user creation, the setValue
function can also be listened to with addOnCompleteListener
, addOnSuccessListener
, addOnFailureListener
.
Ref: Add a Completion Callback.
You need to diagnose the result through these.