Reputation: 2163
I am answering this question then this new question come to my mind.
In that question, I describe my example code like this:
boolean firstCallDone = false;
boolean secondCallDone = false;
DataSnapshot firstDataSnapshot = null;
DataSnapshot secondDataSnapshot = null;
onCreate() {
firstRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
firstCallDone = true;
firstDataSnapshot = dataSnapshot;
if (firsCallDone && secondCallDone)
doSomething();
}
...
}
secondRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
secondCallDone = true;
secondDataSnapshot = dataSnapshot;
if (firsCallDone && secondCallDone)
doSomething();
}
...
}
}
doSomething() {
// do something with firstDataSnapshot and secondDataSnapshot
...
}
The purpose of above code is to execute doSometing()
after two Firebase Database has been called and its values gotten.
Then I realize, instead of validating like this if (firsCallDone && secondCallDone)
, I can validate it like this if (firstDataSnapshot != null && secondDataSnapshot != null)
. That is because as far as I know, DataSnapshot never null (after its value has been filled inside onDataChange()
).
But I am not sure. Is there any chance that DataSnapshot be null inside onDataChange()
? If there is, what is the case that make it happen?
Upvotes: 1
Views: 1216
Reputation: 7720
No, the DataSnapshot
value will never be null
.
If any failure occurs, onCancelled()
method will be triggered instead.
By the way, instead of creating flags to make sure that each listener is finished, you should instead take advantage of Tasks API to manage these tasks. This answer from a Firebaser explains about this and also provides a class for that.
Cheers :)
Upvotes: 1
Reputation: 16319
The DataSnapshot can never be null, regardless of whether there is data there or not (since you'll get an empty but non-null DataSnapshot if there is no data).
Upvotes: 2