使用Firebase的ValueEventListener检测值的变化。

huangapple go评论75阅读模式
英文:

Detect value change with firebase ValueEventListener

问题

以下是翻译好的内容:

我正在尝试从我的Firebase数据库中检测值的变化。以下是我用于初始化ValueEventListener的代码:

valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        try {
            String customerLocation = String.valueOf(dataSnapshot.getValue());
            Point customerPoint = locationFounder.getPoint(customerLocation);

            if (customerPoint != null) {
                databaseReference.child("isActive").addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        boolean isActive = Boolean.valueOf(String.valueOf(dataSnapshot.getValue()));

                        displayPopUp(isActive, customerPoint, customerLocation);
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
            }
        } catch (Exception e) {
            Log.d("Listener", e.toString());
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
};
destinationReference.addValueEventListener(valueEventListener);

当我想在我的活动中调用此监听器时出现问题。我一直在尝试以下方法:

destinationListener.getValueEventListener().onDataChange(REQUIRED_SNAPSHOT);

我不知道如何获取必需的用于onDataChange的DataSnapshot。我希望能够使用ValueEventListener使其工作,而不是ChildEventListener,如果可能的话。然而,我并不确定这是否是尝试检测值变化的正确方法。如果有任何其他适当的方法,我想了解。

英文:

I am trying to detect value change from my Firebase Database. Here is my code for initializing the ValueEventListener:

valueEventListener = new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            try {
                String customerLocation = String.valueOf(dataSnapshot.getValue());
                Point customerPoint = locationFounder.getPoint(customerLocation);

                if (customerPoint != null) {
                    databaseReference.child("isActive").addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                            boolean isActive = Boolean.valueOf(String.valueOf(dataSnapshot.getValue()));

                            displayPopUp(isActive, customerPoint, customerLocation);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError databaseError) {

                        }
                    });
                }
            } catch (Exception e) {
                Log.d("Listener",e.toString());
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    };
    destinationReference.addValueEventListener(valueEventListener);

Problem occurs when I want to call this listener in my activity. I've been trying with this:

destinationListener.getValueEventListener().onDataChange(REQUIRED_SNAPSHOT);

I do not know how can I get datasnapshot which is required for onDataChange. I would like to get this work with ValueEventListener, not ChildEventListener, if possible. However, I am not pretty sure that this is the right way of trying to detect value change. If there is any other way that will work properly, I'd like to know about it.

答案1

得分: 1

Firebase实时数据库中没有内置的功能在onDataChange方法中告诉你快照下的特定数据发生了什么变化。

如果你想知道哪个具体属性发生了变化,你需要:

  1. 将在onDataChange中获得的快照保存在一个字段中。
  2. onDataChange被调用时,将新快照中的数据与字段中的数据进行比较。

假设你在JSON中有一个节点的引用,在该节点下有一个status属性,你想同时监听整个节点,并检测status是否已更改。

你可以这样做:

// 在你的类中添加一个字段来保存最新的快照
DataSnapshot previousSnapshot;

// 然后添加监听器
databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        boolean wasActive = false;
        if (previousSnapshot != null && previousSnapshot.child("status").exists()) {
            wasActive = dataSnapshot.child("status").getValue(Boolean.class);
        }
        boolean isActive = dataSnapshot.child("status").getValue(Boolean.class);

        if (isActive != wasActive) {
            ... 用户状态已更改
        }

        previousSnapshot = dataSnapshot;
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        throw databaseError.toException(); // 永远不要忽略错误
    }
});
英文:

There is nothing built to the Firebase Realtime Database to tell you what specific data under the snapshot has changed in the onDataChange method.

If you want to know what specific property has change, you'll need to:

  1. Keep the snapshot that you get in onDataChange in a field.
  2. When onDataChange gets called, compare the data in the new snapshot with the data in the field.

Say that you have a reference on a node in your JSON, and under that node is a status property, and you want to both listen to the entire node, and detect if the status has changed.

You'd do that with something like:

// Add a field to your class to keep the latest snapshot
DataSnapshot previousSnapshot;

// Then add your listener
databaseReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        bool wasActive = false;
        if (previousSnapshot != null && previousSnapshot.child("status").exists()) {
            wasActive = dataSnapshot.child("status").getValue(Boolean.class);
        }
        boolean isActive = dataSnapshot.child("status").getValue(Boolean.class);

        if (isActive <> wasActive) {
            ... the user's status changed
        }

        previousSnapshot = dataSnapshot;
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        throw databaseError.toException(); // never ignore errors
    }
});

huangapple
  • 本文由 发表于 2020年4月11日 00:37:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/61144646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定