Firebase Realtime Database - Auto Generate Primary Key

Viewed 2662

I am writing some data to a Firebase Realtime Database.

User Class

data class User(
    @Exclude var userId: String? = "",
    var username: String? = "",
    var email: String? = ""
)


Write Function

class MainActivity : AppCompatActivity() {

    private lateinit var mDatabase: DatabaseReference

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

        mDatabase = FirebaseDatabase.getInstance().reference

        bt_register_button.setOnClickListener {
            val username = et_register_username.text.toString()
            val email = et_register_email.text.toString()

            writeNewUser("1", username, email)
        }

    }

    private fun writeNewUser(userId: String, username: String, email: String?) {
        val user = User(username, email)
        mDatabase.child("users").child(userId).setValue(user)
    }

}


Using the above, I can create a User record with a preset Id of 1:


users
     1
          email: "bill@gmail.com"
          username: "bill"

I obviously want the Id to be generated automatically upon creation.

I am aware of the push() function but I'm not sure how to implement it.



Edit 1

Thank you, the User key is now being set as the User UID (from Authentication):

    private fun writeNewUser(name: String, email: String?) {
        val user = User(name, email)
        mDatabase.child("Users").child(mAuth.currentUser!!.uid).setValue(user)
    }

Authentication + Write Database Result

2 Answers

Just call push() instead of child(userId):

mDatabase.child("users").push().setValue(user)

try this code to create auto generated key for firebase realtime database

Using push()

myRef.child(APP_TABLE).child(USER_TABLE).push().setValue(detail)

Using Authentication Current UUID key

myRef.child(APP_TABLE).child(USER_TABLE).child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(detail)
Related