【发布时间】:2022-01-18 01:00:00
【问题描述】:
我以前问过这个问题,但我没有得到任何答案。我正在尝试根据从我的 firebase 数据库中检索到的另外两个文本视图的结果来更新文本视图。
我从这个代码块中获取收入
incomeSumReference.addValueEventListener(object : ValueEventListener {
@SuppressLint("SetTextI18n")
@RequiresApi(Build.VERSION_CODES.N)
override fun onDataChange(snapshot: DataSnapshot) {
var sum = 0.0
for (dataSnapshot in snapshot.children) {
val map = dataSnapshot.getValue() as Map<*, *>
val sumOfIncomes = map.get("itemValue")
val sumo = sumOfIncomes.toString()
val sumAsDouble: Double = sumo.toDouble()
sum += sumAsDouble
val stringSum = sum.toString()
incomeSumToFormated = formatNumberString(stringSum)
profitTextView.text = "+$" + incomeSumToFormated.toString()
}
}
override fun onCancelled(error: DatabaseError) {
}
})
这是用于检索花费的代码块
val spentSumReference = database.getReference("users").child(uid).child("Expenses").child(
currentYear.toString()
).child(currentMonthInString.toString())
spentSumReference.addValueEventListener(object : ValueEventListener {
@RequiresApi(Build.VERSION_CODES.N)
override fun onDataChange(snapshot: DataSnapshot) {
var sum = 0.0
for (dataSnapshot in snapshot.children) {
var map = dataSnapshot.getValue() as Map<String, Object>
val sumOfIncomes = map.get("itemValue")
var sumo = sumOfIncomes.toString()
var sumAsDouble: Double? = sumo.toDouble()
sum += sumAsDouble!!
var stringSum = sum.toString()
var spentSumToFormated =
formatNumberString(stringSum) // this is what I want to get outside
spentTextView.text = "-$" + spentSumToFormated.toString()
}
countExecutedMethods++
}
override fun onCancelled(error: DatabaseError) {
}
})
我想让我的 balanceTextView 显示收入和花费的差异。 但我不能这样做,因为最初它们被设置为 null。
运行代码之前
fun getBalance(){
val total = income-spent
balanceTextView.text = "$total"
}
我必须确保从 firebase 检索数据的函数 getIncome() 和 getExpense() 已经执行。我尝试了很多方法,但并不幸运。最好的方法是什么?
【问题讨论】:
-
你试过使用嵌套监听器吗?
-
您是否建议不要创建两个函数 getExpense() 和 getIncome(),而是创建一个函数,例如:getCurrentMonthData,并使用嵌套侦听器获取所需数据并在它们下尝试 getBalance() 函数? @AlexMamo
-
是的,完全正确。试一试,告诉我它有效。
-
我完全按照你说的做了。它现在似乎工作得很好。我将在下面发布我的答案,您可以查看。 @AlexMamo
标签: android database firebase kotlin firebase-realtime-database