Firebase - 有时值不保存

时间:2016-08-12 06:09:31

标签: android firebase firebase-realtime-database

看看我录制的这个GIF:

(GIF

这是我正在制作的计数器应用程序的数据库。当用户增加时,count会与<{p}}下的count一起添加

users:{
   UID:{
     count: x
   }
}

但是,如果您在GIF中注意到,有时候,上限计数会增加,但users下的计数则不会增加。这是我用它保存的代码:

database = database.child("users").child(auth.getCurrentUser().getUid()).child("count");
    final DatabaseReference finalDatabase = database;
database.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //Get the latest int
            final int[] i = {Integer.parseInt(button.getText().toString())};
            //add to the user's count with an onFailureListener
            finalDatabase.setValue(i[0]++).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG,"Adding user's count failed: " + e.getMessage());
                }
            }).addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    //Now add to the original
                    DatabaseReference database = FirebaseDatabase.getInstance().getReference();
                    database.child("Campaigns").child(key).child("count").setValue(i[0]++).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception e) {
                            Log.e(TAG, "Error: " + e.getMessage());
                        }
                    });
                }
            });

没有onFailure方法被调用。那为什么会这样呢?

1 个答案:

答案 0 :(得分:1)

您可以听取users节点来计算总计数。这是一个例子

private Map<String, Long> userCount = new HashMap<>();
private Long totalCount = 0L;

private void addTotalCountListener() {
    FirebaseDatabase.getInstance().getReference().child("users").addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            User user = dataSnapshot.getValue(User.class);
            userCount.put(dataSnapshot.getKey(), user.getCount);
            totalCount += user.getCount();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            // subtract the total count with the previous count
            totalCount -= userCount.get(dataSnapshot.getKey());
            // then add the new count
            User user = dataSnapshot.getValue(User.class);
            userCount.put(dataSnapshot.getKey(), user.getCount);
            totalCount += user.getCount();
        }
    });
}