How do update one variable from a object in kotlin

1.4k Views Asked by At

I have made a data class of vars (uid, name, age, description, email) and connected to to Cloud Firestore and uploaded data. But when I am updating these descriptions for a user later on in edit page, it is only updating Description and making everything else set to null.

This is my user object:

data class user(
    var uid: String? = null,
    var name: String ?= null,
    var age: String ?= null,
    var des: String ?= null,
    var email: String ?= null

)

This is where I am getting the current user and updating the description :

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

    var db = FirebaseFirestore.getInstance()
    val cities = db.collection("users")

    post.setOnClickListener {
        val post_text = Description.text.toString()

        if(post_text.isEmpty()){
            Toast.makeText(this, "Post is Empty", Toast.LENGTH_SHORT).show()
            return@setOnClickListener
        }
        else{
            //taiking the user based on uid and updating Description 
            val data1 = user(Firebase.auth.currentUser!!.uid)
            data1.des = post_text

            data1.uid?.let { it1 -> cities.document(it1).set(data1) }
        }
    }
2

There are 2 best solutions below

0
On

There is no way to update just some fields when you pass a Java object to set. If you only want to update specific fields, you'll have to pass a map with the values you want to update:

val data1 = mapOf(
  Firebase.auth.currentUser!!.uid to "uid", 
  post_text to "des"
)

data1.uid?.let { it1 -> cities.document(it1).update(data1) }
0
On

I had to update my data in cloud firebase and not put it back again new. //Correct code

        if(post_text.isEmpty()){
            Toast.makeText(this, "Post is Empty", Toast.LENGTH_SHORT).show()
            return@setOnClickListener
        }
        else{
            val data1 = user(Firebase.auth.currentUser!!.uid)
            db.collection("users").document(Firebase.auth.currentUser!!.uid)
                .update("des",post_text)
        }

        back.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }