onDataChange is getting called twice in android Firebase

送分小仙女□ 提交于 2020-01-24 02:12:04

问题


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")
    }
};

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


回答1:


There are 2 scenarios where this may happen:

  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.

  2. 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.

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. 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.



回答2:


Use SingleEventListener instead of ValueEventListener Like this

Firebase ref = new Firebase("YOUR-URL-HERE/PATH/TO/YOUR/STUFF");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot dataSnapshot) {
       String value = (String) dataSnapshot.getValue();
       // do your stuff here with value
   }
   @Override
   public void onCancelled(FirebaseError firebaseError) {
   }
});



回答3:


Replace your query by adding endAt() like below. It will help you.

Query recentStaticJobQuery = reference.child(AppConstants.WORKINDIA_JOBS)
                        .child(AppConstants.WORKINDIA_STATIC_JOBS)
                        .orderByChild(AppConstants.TIMESTAMP)
                        .startAt(lastStaticJobSyncTime).endAt(lastStaticJobSyncTime+"\uf8ff"); 


来源:https://stackoverflow.com/questions/39304670/ondatachange-is-getting-called-twice-in-android-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!