0
private boolean authenticateUser(final String role, final String userId) {
    DatabaseReference roleReference = FirebaseDatabase.getInstance().getReference().child("role").child(role);
    roleReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            HashMap<String, String> map = (HashMap<String, String>) dataSnapshot.getValue();
            if (map != null) {
                Set<String> userIds = map.keySet();
                if (userIds.contains(userId))
                    authenticationResult = true;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    return authenticationResult;
}

Above is a function to authenticate user. I want to return true if (userIds.contains(userId)) else false. But the authenticateUser always returns false.

sanidhya pal
  • 345
  • 1
  • 9
  • 1
    The asynchronous nature of the listener callbacks is explained in this answer: http://stackoverflow.com/a/41409942/4815718 – Bob Snyder Apr 23 '17 at 15:38

1 Answers1

0

If you are sure that the code has no errors, I would like to remind you that Firebase connections are async. That said, you can not use an async method to return a value, because the return sentence is going to be executed before you have enough time to change that boolean.

Try changing the method so it returns void and inside onDataChange use a kind of response method with the value.

Example:

private void authenticateUser(final String role, final String userId) {
DatabaseReference roleReference = FirebaseDatabase.getInstance().getReference().child("role").child(role);
roleReference.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        HashMap<String, String> map = (HashMap<String, String>) dataSnapshot.getValue();
        if (map != null) {
            Set<String> userIds = map.keySet();
            if (userIds.contains(userId))
                authenticationResult = true;
        }
        authenticateUserResponse(authenticationResult);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

That will be the only way to do it properly, since async methods are not meant to return values before the job was done.

JMedinilla
  • 481
  • 5
  • 15