Reputation: 97
I need to get Firebase Database current milliseconds epoch time in Kotlin Android app, i tried to push the value to firebase and then read it, i have a button calls a function named pushEndTime() then calls read() but it always get's null value on the first click then on the second click it get's the past value of endTime
this is the code:
private fun pushEndTime(){
rootRef.child("user/endTime").setValue(ServerValue.TIMESTAMP)
}
then i read it using
private fun read(){
rootRef.child("user/endTime").addValueEventListener(
object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
endTime = dataSnapshot.value.toString()
}
override fun onCancelled(databaseError: DatabaseError) {
Log.w(TAG, "LoginData:onCancelled", databaseError.toException())
Toast.makeText([email protected], "Error! check your internet", Toast.LENGTH_LONG)
.show()
}
})
}
i use these methods in onActivityCreated
like this :
button.setOnClickListener {
pushEndTime()
read()
}
i can't put pushEndTime()
in onActivityCreated
, it has to be inside a function creates endTime once the button is clicked and some other values checked, but i also tried to put it inside on create and still returns null result on the first button click
I found some answers here suggesting to use Firebase.database.ServerValue.TIMESTAMP
but it dosen't work for me
this is how i used it: endTime = ServerValue.TIMESTAMP.getValue(".sv")
but it returns this value and not the epoch time: Timestamp
i tried this: Firebase.database.ServerValue.TIMESTAMP.getValue(".sv")
but it shows unresolved reference: ServerValue
error
also i tried it like this: Firebase.database.reference.ServerValue.TIMESTAMP.getValue(".sv")
and the same unresolved reference error
com.google.firebase.database.ServerValue is imported
I need to get firebase server time, if there is defiantly no way, how to get the internet time in kotlin?
Upvotes: 1
Views: 1391
Reputation: 5644
You can try this:
private fun pushEndTime(){
rootRef.child("user/endTime").setValue(ServerValue.TIMESTAMP).addOnSuccessListener {
read()
}
}
private fun read(){
rootRef.child("user/endTime").addListenerForSingleValueEvent(
object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
endTime = dataSnapshot.value.toString()
}
override fun onCancelled(databaseError: DatabaseError) {
Log.w("SignedActivity.TAG", "LoginData:onCancelled", databaseError.toException())
}
})
}
Call read method when setValue is success
Upvotes: 1