Firebase数据库无法写入数据

时间:2016-12-21 14:43:33

标签: java firebase firebase-realtime-database

我正在使用google app engine + firebase数据库。我需要通过app引擎更改firebase数据库中的某些值,但setValue()方法不起作用。没有发送异常,我可以读取数据,因此服务帐户运行良好。 这是我使用的代码:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");

  ref.addListenerForSingleValueEvent(new ValueEventListener() {
     @Override
        public void onDataChange(DataSnapshot snapshot)
        {
            if (snapshot.exists())
            {
                for (DataSnapshot childSnap : snapshot.getChildren()) {
                    if (childSnap.child("Character").exists()) {
                        int energyCurrent;
                        int energyMax;
                        int energyObtain;
                        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();

                        float finalEnergy = energyCurrent + (energyMax * (energyObtain / 100));
                        if (finalEnergy > energyMax) {
                            childSnap.getRef().child("Character").child("energyCurrent").setValue(energyMax, new DatabaseReference.CompletionListener() {
                                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                                    if (databaseError != null) { throw databaseError.toException(); }
                                }
                            });
                        } else {
                            childSnap.getRef().child("Character").child("energyCurrent").setValue((int) finalEnergy, new DatabaseReference.CompletionListener() {
                                public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
                                    if (databaseError != null) { throw databaseError.toException(); }
                                }
                            });
                        }
                    }
                }
            }
}

Here is the scheme of my database if u need it:

    "Users" : {
        "NRPdi5gaaaaaHSfovegwg8XgFjZ2" : {
          "Character" : {
            energyCurrent : 0,
            energyMax : 100,
            energyObtain : 20,
            and other char values..
          }
        }
    } 

1 个答案:

答案 0 :(得分:3)

energyObtain = (int) (long) childSnap.child("Character").child("energyObtain").getValue();

并且

energyObtain : 20,

然后这只是零。

(energyMax * (energyObtain / 100));

所以,解决方案......制作一个合适的浮点

energyMax * (energyObtain / 100.0)