petter-odden
petter-odden

Reputation: 11

Firebase realtime database setValue() not working

I am trying to write some basic information about users to a Firebase realtime database, but when running setValue() nothing happens in the console and after many hours of trying I still can't figure out the problem.

This is the code in the fragment that calls the registerUser function:

registerButton.setOnClickListener {

        firstNameLayout.error = null
        lastNameLayout.error = null
        emailFieldLayout.error = null
        passwordFieldLayout.error = null

        var fieldCheck = true

        if(TextUtils.isEmpty(firstNameField.text)) {
            firstNameLayout.error = "Please Enter First Name";
            fieldCheck = false
        }
        if (TextUtils.isEmpty(lastNameField.text)) {
            lastNameLayout.error = "Please Enter Last Name"
            fieldCheck = false
        }
        if(TextUtils.isEmpty(emailField.text)) {
            emailFieldLayout.error = "Please Enter Email Address";
            fieldCheck = false
            // Todo: Make sure format is correct
        }
        if(TextUtils.isEmpty(passwordField.text)){
            passwordFieldLayout.error = "Please Choose a Password"
            fieldCheck = false
            // Todo: Stricter password requirements 
        }
        if(!fieldCheck) {
            return@setOnClickListener
        }

        registerButton.startAnimation()

        val fName = firstNameField.text.toString().trim()
        val lName = lastNameField.text.toString().trim()
        val email = emailField.text.toString().trim()
        val password = passwordField.text.toString().trim()

        try {
            registerButton.doneLoadingAnimation(2, bitmap)
            (activity as LoginRegister).registerUser(email, password, fName, lName)

        } catch (e: Exception) {
            Toast.makeText(activity, e.message, Toast.LENGTH_SHORT).show()
            registerButton.revertAnimation()
        }

    }

This is the registerUser function body from the parent activity of the fragment:

fun registerUser(email: String, password: String, fName: String, lName: String) {
    //Registrerer med Firebase Authentication
    auth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this) { task ->
            if (task.isSuccessful) {
                // Sign in success, update UI with the signed-in user's information
                Log.d(TAG, "createUserWithEmail:success")
                val user : FirebaseUser = task.result!!.user!!
                val uid: String = user.uid
                val dbUser = User(fName, lName, email)

                writeNewUser(uid, dbUser)

                val intent = Intent(this@LoginRegister, MainActivity::class.java)
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                intent.putExtra("user_email", email)
                intent.putExtra("user_first_name", fName)
                intent.putExtra("user_last_name", lName)
                startActivity(intent)
                finish()

            } else {
                // If sign in fails, display a message to the user.
                Log.w(TAG, "createUserWithEmail:failure", task.exception)
                Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show()
            }
        }



}

This is the writeNewUser function body

fun writeNewUser(userId: String, user: User) {
    database = FirebaseDatabase.getInstance().getReference("Users").child(userId)
    database.child("users").child(userId).setValue(user)
}

The User object is instantiated from this kotlin class:

data class User(val fName: String? = null, val lName: String? = null, val email: String? = null) {
val firstName = fName?.capitalize(Locale.ROOT)
val lastName = lName?.capitalize(Locale.ROOT)
val emailAddress = email

}

Firebase:

Firebase nodes

Anyone know the reason behind this?

Upvotes: 0

Views: 1354

Answers (3)

Vasco28
Vasco28

Reputation: 21

put the URL of database in the getInstance() was the solution for me, now it works perfect

example:

private val database = FirebaseDatabase.getInstance("https://conect-c91b3-default-rtdb.firebaseio.com/").getReference()

// to test if is working
database.child("users").setValue("test")

Upvotes: 2

petter-odden
petter-odden

Reputation: 11

I solved it, I was using another database location than the default, and I didn't catch the fact that I needed to pass the database URL in the getInstance() method. Passing the correct database url fixed the issue

Upvotes: 1

Zain
Zain

Reputation: 40898

fun writeNewUser(userId: String, user: User) {
    database = FirebaseDatabase.getInstance().getReference("Users").child(userId)
    database.child("users").child(userId).setValue(user)
}

I guess you duplicate a couple of child nodes in above snippet as it implies a group of users has a single user, and this particular user has a group of users, doesn't make sense, so you can remove these duplicates:

fun writeNewUser(userId: String, user: User) {
    database = FirebaseDatabase.getInstance().getReference("Users").child(userId)
    database.setValue(user)
}

UPDATE:

enter image description here

The firebase nodes are case-sensitive, so change "Users" to lowercase "users"

fun writeNewUser(userId: String, user: User) {
    database = FirebaseDatabase.getInstance().getReference("users").child(userId)
    database.setValue(user)
}

Upvotes: 0

Related Questions