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?
There are 2 scenarios where this may happen:
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
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:
runnable.postDelayed(callbackRunnable, 3000);
to wait for the latest value for 3 seconds before updating the views or whatever you want to update.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) {
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With