Firebase在触发onChildChange()之前获取值

时间:2016-07-20 11:22:16

标签: android firebase firebase-realtime-database

我希望在func onChildChange()发生之前从我的Firebase树中获取旧值。是不可能的?我有很多孩子和Listener ForSingleEventValue不是我的解决方案,所以我只需要关注事件onChildChange,但我无法从已被修改的子项中捕获旧值。欢迎任何帮助!
enter image description here

例如,我想监视一个孩子" StatusEntry"如果状态改变,则在onChildChange()中触发一些func。但我希望得到它的旧价值。

public void onChildChanged(DataSnapshot dataSnapshot, String s) {
Map<String, Object> newPost1 = (Map<String, Object>) dataSnapshot.getValue();
for (Map.Entry<String, Object> entryDate : newPost1.entrySet()) {

Map<String, Object> newPost2 = (Map<String, Object>) entryDate.getValue();
for (Map.Entry<String, Object> entryService : newPost2.entrySet()){

Map<String, Object> newPost3 = (Map<String, Object>) entryService.getValue();
for (Map.Entry<String, Object> entryTime : newPost3.entrySet()){
Map<String, Object> newPost4 = (Map<String, Object>) entryTime.getValue();
for (Map.Entry<String, Object> entry : newPost4.entrySet()){
     if (entry.getKey().equals("StatusEntry")){
     Log.e("StatusEntry",entry.getValue().toString());
     myfunction();
     }
}}}}
}

1 个答案:

答案 0 :(得分:0)

由于所有这些内部循环,我会重构你的代码,但你可以通过设置外部变量来获得旧的和新的值。您如何做到这一点将取决于您当前的实施。

private String oldValue = null;

public void onChildChanged(DataSnapshot dataSnapshot, String s) {
    String newValue = dataSnapshot.getValue().toString();
    // your logic with old and new value
    oldValue = newValue;
}

另一种可能的解决方案是在数据库的新分支中跟踪旧值,并在调用onChildAdded时检索它。