Android Firebase Wait For Data
in my android application I create an activity which contains a ListView which is populated with data from Firebase Database. The JSON Tree of the structure of the database is the
Solution 1:
You can use a simple counter to keep track of the number of pending loads:
companyRequests.addValueEventListener(newValueEventListener() {
publicvoidonDataChange(DataSnapshot dataSnapshot) {
// at the start we need to still load all childrenfinallong[] pendingLoadCount = { dataSnapshot.getChildrenCount() };
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
//For each key I retrieve its details from the requests nodeDatabaseReferencecurrRequest= rootNode.child("requests/" + childSnapshot.getKey());
currRequest.addListenerForSingleValueEvent(newValueEventListener() {
publicvoidonDataChange(DataSnapshot dataSnapshot) {
String time;
time = (String) dataSnapshot.child("time").getValue();
Requestrequest=newRequest(time);
allRequests.add(request);
// we loaded a child, check if we're done
pendingLoadCount[0] = pendingLoadCount[0] - 1;
if (pendingLoadCount[0] == 0) {
RequestAdapteradapter=newRequestAdapter(RequestsListActivity.this, allRequests);
rListView.setAdapter(adapter);
}
}
...onCancelled...
});
}
}
});
Solution 2:
I solved this using a java.util.concurrent.CountDownLatch:
In this example, replace EquityTotalListener with your implementation of ValueEventListener.
privatevoidrecalculate() {
finalAtomicLongsumUpAll=newAtomicLong();
finalCountDownLatchcnt=newCountDownLatch(mapUid2GeoLocation.keySet().size());
for (final String uid : mapUid2GeoLocation.keySet()) {
EquityTotalListenerel= mapUid2EquityListener.get(uid);
if (el != null) {
if (logger.isDebugEnabled()) {
logger.debug("Listener for " + uid + " already set up");
cnt.countDown();
}
} else {
el = newEquityTotalListener(database.getDatabase(), uid) {
@OverridepublicvoidonCancelled(final DatabaseError databaseError) {
super.onCancelled(databaseError);
cnt.countDown();
}
@OverrideprotectedvoidvalueChanged(final String key, final Object value) {
if (value != null) {
sumUpAll.getAndAdd(Long.parseLong(value.toString()));
cnt.countDown();
}
};
}.attach();
mapUid2EquityListener.put(uid, el);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Waitung for countdown..");
}
try {
finalbooleanallGood= cnt.await(10, TimeUnit.SECONDS);
if (allGood) {
if (logger.isDebugEnabled()) {
logger.debug("Done waiting, " + uid + " owns " + sumUpAll.get() + " equity");
}
} else {
if (logger.isWarnEnabled()) {
logger.warn("Waiting for read operations ran into timeout");
}
}
} catch (final InterruptedException e) {
if (logger.isErrorEnabled()) {
logger.error(e.getLocalizedMessage(), e);
}
}
}
Post a Comment for "Android Firebase Wait For Data"