我需要在Android应用中增加每个用户的能量值。
以下是我的数据库方案:
"Users" : {
"NRPdi5gzbsWoHSfovOtIO8XgFjZ2" : {
"Character" : {
energyCurrent : 0,
energyMax : 100,
energyObtain : 20,
and other char values..
}
}
}
我阅读,使用此代码进行一些计算和编写数据,但我的Firebase数据库中没有任何变化。此代码位于Google App Engine上。没有例外发送,没有任何反应。
final FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference ref = db.getReference("Users");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot childSnap : snapshot.getChildren()) {
int energyCurrent;
int energyMax;
int energyObtain;
try {
energyCurrent = (int) childSnap.child("Character").child("energyCurrent").getValue();
energyMax = (int) childSnap.child("Character").child("energyMax").getValue();
energyObtain = (int) childSnap.child("Character").child("energyObtain").getValue();
}
catch (Exception e)
{
continue;
}
float finalEnergy = energyCurrent + (energyMax * (energyObtain/100));
if (finalEnergy > energyMax){
DatabaseReference reference = childSnap.getRef().child("Character").child("energyCurrent");
reference.setValue(energyMax, new DatabaseReference.CompletionListener() {
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
throw databaseError.toException();
}
});
}
else
{
DatabaseReference reference = childSnap.getRef().child("Character").child("energyCurrent");
reference.setValue((int)finalEnergy, new DatabaseReference.CompletionListener() {
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
throw databaseError.toException();
}
});
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
答案 0 :(得分:1)
以下语句会为循环的每次迭代抛出异常:
energyCurrent = (int) childSnap.child("Character").child("energyCurrent").getValue();
数字字符串上的 getValue()
会返回Long
,无法将其取消装箱到int
,而是抛出:
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
catch-block中的continue
语句将控制转移到循环体的末尾,跳过包含对setValue()
的调用的代码。
您可以对三个语句使用双重转换:
int energyCurrent = (int)(long) dataSnapshot.child("count").getValue();
或者制作变量long
并使用单个(long)
演员:
long energyCurrent;
long energyMax;
long energyObtain;
答案 1 :(得分:1)
你不能在long变量中强制转换整数,如果你坚持使用它,强制转换:
try {
energyCurrent = (int)(long) childSnap.child("Character").child("energyCurrent").getValue();
energyMax = (int)(long) childSnap.child("Character").child("energyMax").getValue();
energyObtain = (int)(long) childSnap.child("Character").child("energyObtain").getValue();
}
你应该删除:
throw databaseError.toException();
<完成数据库上的