[英]Retrieve integer from Firebase child
I am trying to implement a counter for deals in my app.我正在尝试在我的应用程序中实现交易计数器。 i am trying to recall the last integer written to the child eg deal number 10. i can successfully write a manually inputted value into firebase however i cannot retrieve the initial value.
我试图回忆写给孩子的最后一个整数,例如交易号 10。我可以成功地将手动输入的值写入 firebase,但是我无法检索初始值。
i am using the following我正在使用以下
dealnumRef = FirebaseDatabase.getInstance().reference
val numberRef = dealnumRef.child("Total_deals").orderByChild("deal_number")
val dealnumEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val deal_num =
ds.child("deal_number_cars").getValue()
d("current deal number",deal_num.toString())
val new_deal_num = deal_num + 1
the issue i have is that currently deal_num
is pulling through as Any?
我遇到的问题是目前
deal_num
正在通过Any?
. . If i insert
String::class.java
into getvalue()
it will bring it back as a string.如果我将
String::class.java
插入到getvalue()
中,它会将其作为字符串返回。 But I need to keep it as an Integer
to compute new_deal_num
because new_deal_num
will need to be written to the database and increment the deal_number
to 11 as an example.但我需要将其保留为
Integer
以计算new_deal_num
,因为new_deal_num
需要写入数据库并将deal_number
增加到 11 作为示例。
how do i extract deal_num
as an integer?我如何将
deal_num
提取为整数?
I have checked available answers, but those indicate to convert to string.我检查了可用的答案,但那些表明要转换为字符串。 This would not work in my example, because i need to increment the deal number and hence keep it as an integer.
这在我的示例中不起作用,因为我需要增加交易编号并因此将其保持为整数。
You can get the correct type from Firebase by passing its class into getValue(..)
.您可以通过将其类传递到
getValue(..)
来从 Firebase 获取正确的类型。
So:所以:
val deal_num = ds.child("deal_number_cars").getValue(Long.class)
If you're storing a number in deal_number_cars
in the database, this will get that value as a long
.如果您在数据库中的
deal_number_cars
中存储一个数字,这将获得该值作为long
。
The Full correction to the above is as follows:对上述内容的完整更正如下:
dealnumRef = FirebaseDatabase.getInstance().reference
val numberRef = dealnumRef.child("Total_deals").orderByChild("deal_number_cars")
val dealnumEventListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (ds in dataSnapshot.children) {
val deal_num =
ds.getValue(Long::class.java)!!
d("current deal number",deal_num.toString())
val new_deal_num = deal_num + 1
You also have to make sure that you data model class is set as Long.您还必须确保您的数据模型类设置为 Long。 i originally had it set as Int which created a small problem but was easily resolved.
我最初将它设置为 Int,这会产生一个小问题,但很容易解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.