问题描述
在我的数据库中,我跟踪用户的行进距离,并将每个人的初始值设置为0.在我的代码中,我通过获取旧值并为其添加新距离,然后保存该值来更新此值.
In my database, I'm keeping track of the distance travelled by users and set an initial value of 0 for everyone. In my code, I am updating this value by getting the old value and adding the new distance to it, then saving that value.
首先,当我从数据库中检索0时,它以Long形式返回,这很好:
At first, when I retrieve the 0 from the database, it is returned as a Long, which is fine:
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Long previousDistance = (Long) dataSnapshot.child("distance").getValue();
userReference.child("distance").setValue(previousDistance.doubleValue()+distanceTravelled);
}
问题在于,现在,存储在数据库中的值是Double,因此,下次运行上述代码时,它将失败,并显示ClassCastExcepiton
.
The problem is that now, the value stored in the database is a Double, so next time the above code is run it will fail with a ClassCastExcepiton
.
我可能可以使用if语句解决问题,但最简单的解决方案是将初始0存储为Double.但是,我无法做到这一点.我已经尝试过这两种方法:
I could probably solve the issue with an if statement, but the easiest solution would be to store the initial 0 as a Double instead. However, I can't make that work. I've tried both of these:
myDatabase.child("users").child(lowerCaseUserName).child("distance").setValue(Double.valueOf(0.0));
myDatabase.child("users").child(lowerCaseUserName).child("distance").setValue(0.0);
它们仍然存储为"0",并以Long形式返回.是否可以将零作为Double存储在数据库中?
They still get stored as "0" and returned as a Long. Is it possible to store zero as a Double in the database?
推荐答案
它不存储为"0"(字符串),而是存储为数字0.在Firebase中,不管您使用哪种原始类型只要它是0(零)就可以存储.如果将现有值0(零)添加为0.01,结果将为: 0.01
,显然是Double.
It isn't stored as "0" (String) it is stored as the number 0. In Firebase, it doesn't matter what kind of primitve you are storing, as long as it is a 0 (zero). If you add to an existing value of 0 (zero), 0.01, the result will be: 0.01
, which obviously is a Double.
要记住的一件事是,在存储数据的同一时间从数据库中获取数据.如果您使用以下代码行将值设置为Double:
One thing to remember is to get the data from your database in the same wasy you are storing it. If you are setting a value as a Double using this line of code:
myDatabase.child("users").child(lowerCaseUserName).child("distance").setValue(0.01);
如果只需要0(零),则只能使用:
If you want only a 0 (zero), you can only use:
myDatabase.child("users").child(lowerCaseUserName).child("distance").setValue(0);
并且要找回它,您需要使用以下代码行:
And to get it back, you need to use this line of code:
double previousDistance = dataSnapshot.child("distance").getValue(Double.class);
这篇关于如何在Firebase数据库中将零保存为Double的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!