onDataChange在android Firebase中被调用了两次 [英] onDataChange is getting called twice in android Firebase

查看:59
本文介绍了onDataChange在android Firebase中被调用了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在android应用中使用时间戳对Firebase数据进行的简单查询

Here is My simple query for firebase data using timestamp in android app

Query recentStaticJobQuery = reference.child(AppConstants.WORKINDIA_JOBS)
                        .child(AppConstants.WORKINDIA_STATIC_JOBS)
                        .orderByChild(AppConstants.TIMESTAMP)
                        .startAt(lastStaticJobSyncTime); 
recentStaticJobQuery.addListenerForSingleValueEvent
(staticJobDownloadListener);


 ValueEventListener staticJobDownloadListener = new ValueEventListener() {
    @Override
    public void onDataChange(final DataSnapshot dataSnapshot) {
        Log.i("Firebase", "Called")
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        Log.i("Firebase", "onCancelled")
    }
};

如何避免onDataChange在Android Firebase中被调用两次?

How to avoid onDataChange to get called twice in android Firebase?

推荐答案

在两种情况下可能会发生这种情况:

There are 2 scenarios where this may happen:

    如果启用了脱机持久性,则调用
  1. onDataChange两次.一次使用陈旧的离线值,再次使用更新后的值(以防更改).

  1. onDataChange is called twice in case you have enabled offline persistence. Once with the stale offline value and again with the updated value in case it has changed.

onDataChange被多次调用,以防您没有正确删除侦听器,并且每次打开它都会在您的活动中创建新的侦听器实例.

onDataChange is called multiple times in case you have not removed the listener properly and are creating a new instance of your listener in your activity every time you open it.

方案2易于修复.与在Activity的onDestroy中执行ref.removeListener(listener)相比,您可以维护Firebase参考和侦听器的本地参考.方案2很难解决,您有2种可能的补救措施:

Scenario 2 is easy to fix. You can maintain local references of your firebase reference and listener, than you can do a ref.removeListener(listener) in onDestroy of your Activity. Scenario 2 is difficult to fix and you have 2 possible remedies:

  1. 如果始终需要更新的最新值,请禁用离线持久性.
  2. 执行runnable.postDelayed(callbackRunnable, 3000);键等待最新值3秒钟,然后再更新视图或您要更新的任何内容.
  1. Disable offline persistence in case you always want the updated latest value.
  2. Do a runnable.postDelayed(callbackRunnable, 3000); to wait for the latest value for 3 seconds before updating the views or whatever you want to update.

这篇关于onDataChange在android Firebase中被调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆