Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onDataChange is getting called twice in 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")
    }
};

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

like image 852
Lokesh Tiwari Avatar asked Sep 03 '16 08:09

Lokesh Tiwari


2 Answers

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.
like image 190
Ajitesh Shukla Avatar answered Oct 31 '22 15:10

Ajitesh Shukla


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) {
   }
});
like image 21
KKumar Technologies Avatar answered Oct 31 '22 16:10

KKumar Technologies