Aleen
Aleen

Reputation: 15

I cannot seem to connect to Firestore database to save user's data

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 get none. It just works but it doesn't add anything new to my Firestore 'user' collection.

Any help would be appreciated. Thank you in advance

Upvotes: 0

Views: 446

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

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.

Upvotes: 1

Abdullah Z Khan
Abdullah Z Khan

Reputation: 1286

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.

Upvotes: 0

Related Questions