Home > Mobile >  how to save an object in object in real-time database, Firebase (kotlin)
how to save an object in object in real-time database, Firebase (kotlin)

Time:06-20

I would like to save data into the real-time database of Firebase, but I run into a problem. I've only been working with Kotlin for 1 month, and unfortunately I don't know how to save data to the real-time database in this form, as shown in the picture.

My current code is this:

data class userData(
    val username: String,
    val uid: String,
)

database = FirebaseDatabase.getInstance().getReference("Userdata")
val user = uid?.let {
    userData("Test1", it)
}

if (uid != null) {
    database.child(uid).setValue(user).addOnSuccessListener {
        Toast.makeText(this, "Success saved", Toast.LENGTH_LONG).show()
    }.addOnFailureListener {
        Toast.makeText(this, "Failed", Toast.LENGTH_LONG).show()
    }
}

My database. The same way, I would like to be able to save it with Kotlin https://i.stack.imgur.com/fbAsC.png

The problem is, I don't know how to save the data object to the database, is there an easy way?

CodePudding user response:

I think what you forgot is to tell the table name inside the database. You should try using database.child(tableName).child(uid).setValue(user) and then the addOnSuccessListener

CodePudding user response:

I would suggest you to improve your data class for userData model like below because there are some cases, you will have error about it in future.

data class userData(
    val username: String? = null,
    val uid: String? = null,
)

To answer your question, you need to create a new data class for the data model like below.

data class UserDataExtra(
    val banned: Boolean? = null
)

Next you just need to implement inside the addOnSuccessListener like below.

if (uid != null) {
    database.child(uid).setValue(user).addOnSuccessListener {
        //Here you will update new model for userDataExtra
        val userExtra = UserDataExtra (false)
        database.child(uid).child("UserDataExtra").setValue(userExtra )..addOnSuccessListener {
            Toast.makeText(this, "Success saved with data extra!", Toast.LENGTH_LONG).show()
        }
    }.addOnFailureListener {
        Toast.makeText(this, "Failed", Toast.LENGTH_LONG).show()
    }
}

CodePudding user response:

Get instance of your database:

val database = Firebase.database.reference

The call to write to your database:

database.child("UserData").child(uid).setValue(user)

To Read from your database once:

database.child("UserData").child(uid).get().addOnSuccessListener {
    Log.i("firebase", "Got value ${it.value}")
}.addOnFailureListener{
    Log.e("firebase", "Error getting data", it)
}

This article has the solution to what you're looking for.
https://firebase.google.com/docs/database/android/read-and-write?hl=en&authuser=0#read_data

It is also possible to listen for changes in your database and update accordingly mentioned in the article above.

  • Related