问题
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:
onDataChangeis 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.onDataChangeis 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:
- Disable offline persistence in case you always want the updated latest value.
- 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