I want to update the data in Firebase when the application terminates. How can I do that
I used onDestroy
and onPause
but they did not do the function I wanted. When I use OnPause, every time the application goes to the background, it does the update operation, and I don't want that either.
// This onDestroy didn't work OnPause, every time the application goes to the background
override fun onDestroy() {
super.onDestroy()
Log.d("ClosingService", "Service is destroyed. Updating user data...")
Update_User_Data(dataManager.userDataList)
}
fun Update_User_Data(newDataList : ArrayList<User_Structure>){
val tasks = newDataList.map { i ->
val userRef = db.collection("users").document(i.userId)
userRef.update(mapOf(
"username" to i.username,
"favorites" to i.favorites,
"parts" to i.parts,
"points" to i.points
))
}
Tasks.whenAllComplete(tasks).addOnCompleteListener {
if (it.isSuccessful) {
println("All user data updated successfully!")
} else {
println("Error updating some user data.")
}
}
}
I used OnDestroy and OnPouse but they did not do the function I wanted.
Please bear in mind, that the onDestroy
is not always called. So you cannot rely on that. As @MarsAtomic already mentioned in his comment, you should consider using onSaveInstanceState() instead which is:
Called to retrieve per-instance state from an activity before being killed so that the state can be restored in
onCreate(Bundle)
oronRestoreInstanceState(Bundle)
.