Return Value From Valueeventlistener Java
I am trying to return a boolean but the value returned is always false, i.e. 0 in this case. The check variable is an instance variable and the below function is getting called whe
Solution 1:
As with all async operations I often do it in a callback manner.
Your solution could work like this:
Create a simple callback interface (I have mine in a library that I use in almost every app)
publicinterfaceSimpleCallback { voidcallback(Object data); } // You could do it as well generic, that's what I do in my lib:publicinterfaceSimpleCallback<T> { voidcallback(T data); }
Then redesign the signature of your method like this:
privatevoidcheckAnswerSubmission(@NonNull SimpleCallback<boolean> finishedCallback) {
DatabaseReference answerDatabase = FirebaseDatabase.getInstance().getReference().child("userPuzzleHistory").child(uid);
answerDatabase.addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
// This will simple call your callback containing a boolean true/false
finishedCallback.callback(dataSnapshot.hasChild(String.valueOf(imagename)));
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
}
});
}
You call this with:
checkAnswerSubmission(newSimpleCallback<boolean>() {
@Overridevoidcallback(boolean data) {
if (data) {
// true was returned
} else {
// false was returned
}
}
});
Solution 2:
The database reference is not done on the same thread as that running your function. It just adds a listener for the async call that is only made when the data is received from server.
So your program initializes a listener and moves on to the next statement in this line.
answerDatabase.addListenerForSingleValueEvent(newValueEventListener() {
@OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild(String.valueOf(imagename))) {
check = 1;
} else {
check = 0;
}
//here the value check is working fine but the value cannot be returned from here.
}
@OverridepublicvoidonCancelled(DatabaseError databaseError) {
}
});
Now as the program doesn't wait for response to be received from the server it executes :
if (check == 1)
returntrue;
elsereturnfalse;
So if your check value was initialized it will most likely take 0 as value and always return false.
Post a Comment for "Return Value From Valueeventlistener Java"