我正在尝试在应用中创建类似功能,类似功能已在运行(递增和递减)。我的问题是我需要再次重新进入活动,以查看类似的新值。但我的实时数据库中的值已经更改,但在应用程序视图中,它不会递增或递减(需要重新输入才能查看新值)。如何在单击按钮时刷新应用中的值?代码如下
//set the likes number on start
likes.text = myPlants.likes.toString();
//When like is clicked
bulbLike.setOnCheckListener(object : OnCheckListener {
override fun onChecked(view: ExpressView?) {
bulbLike(myPlants.plantId,currentUser!!.uid)
//When i remove this the values dosent change
val rootRef = FirebaseDatabase.getInstance().reference
val likeRef = rootRef.child("plants").child(myPlants.plantId).child("likes")
likeRef.get().addOnCompleteListener(OnCompleteListener<DataSnapshot?> { task ->
if (task.isSuccessful) {
val value: Long? = task.result.getValue(Long::class.java)
likes.text = value.toString()
} else {
Log.d("TAG", "Error") //Don't ignore potential errors!
}
})
}
override fun onUnChecked(view: ExpressView?) {
bulbDislike(myPlants.plantId,currentUser!!.uid)
//When i remove this the values dosent change
val rootRef = FirebaseDatabase.getInstance().reference
val likeRef = rootRef.child("plants").child(myPlants.plantId).child("likes")
likeRef.get().addOnCompleteListener(OnCompleteListener<DataSnapshot?> { task ->
if (task.isSuccessful) {
val value: Long? = task.result.getValue(Long::class.java)
likes.text = value.toString()
} else {
Log.d("TAG", "Error") //Don't ignore potential errors!
}
})
}
})
这一个工作它改变值但是它改变为1或-1
这是方法还是喜欢和不喜欢
private fun bulbLike(plantId: String, userId: String) {
val dPlant: DatabaseReference = FirebaseDatabase.getInstance().reference
dPlant.child("plants").child(plantId).child("likes").setValue(ServerValue.increment(1))
dPlant.child("plants").child(plantId).child("userLikes").child(userId).child("status").setValue("Liked")
}
private fun bulbDislike(plantId: String, userId: String) {
val dPlant: DatabaseReference = FirebaseDatabase.getInstance().reference
dPlant.child("plants").child(plantId).child("likes").setValue(ServerValue.increment(-1))
dPlant.child("plants").child(plantId).child("userLikes").child(userId).child("status").setValue("Dislike")
}
1条答案
按热度按时间ff29svar1#
这里获取数据一次,不要在你的情况下使用它:
改为如下所示,使用
ValueEventListener
,如下所示: