Saturday, 5 February 2022

Firebase Firestore: Update a field of a document in a subcollection while retrieving information

New to android. How can I update a field(timestamp, check database pictures) to a document of a subcollection, while getting the the fields of a document? I am unsure how to do so given my setup. It appears that I can't use .update() with my code as is, so I am unsure how to go about this. Let me know if more details is needed.

edit petID is the id belonging to the document in which the subcollection belongs to.

reminderID is the id belonging to the document within the subcollection

class ReminderActivity : AppCompatActivity() {
    lateinit var reminderID: String
   
    val db = Firebase.firestore
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_reminder)

        reminderID = intent.getStringExtra("reminderID").toString()

        val completeTask: Button = findViewById(R.id.complete_button)
        completeTask.setOnClickListener {
            db.collection("pets").document("vNkkDGAS1oBMpanEXhte").collection("reminders").document(reminderID).get().addOnSuccessListener { document ->
                    val timeStamp = document.get("timestamp") as com.google.firebase.Timestamp
                    val millisec = timestamp.seconds * 1000 +timestamp.nanoseconds/1000000
                    val netDate = Date(millisec)
                    val frequency = document.get("frequency").toString()
                    val cal: Calendar = Calendar.getInstance()
                    cal.time = netDate

                    when(frequency) {
                        ("Every Day") -> cal.add(Calendar.DATE, 1)
                        ("Every Week") -> cal.add(Calendar.WEEK_OF_MONTH, 1)
                        ("Every Month") -> cal.add(Calendar.MONTH, 1)
                        ("Every Year") -> cal.add(Calendar.YEAR, 1)
                        else -> { }
                    }
                    
                    val time = Timestamp(cal.timeInMillis)
                    document.update({timestamp: time}) //<- line not working
                }
        }
    }
}

pictures of cloud firestore database enter image description here

enter image description here

enter image description here



from Firebase Firestore: Update a field of a document in a subcollection while retrieving information

No comments:

Post a Comment