0

This is my function that calls the two other functions that crash my app. I know it crashes because the retrieval function in database is asynchronous. I faced this in developing the iOS App, is there a way to make this work properly?

private void FetchMatchInformation(String key) {

    final DatabaseReference userDb = FirebaseDatabase.getInstance().getReference().child("Users").child(key);

    userDb.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
       if (dataSnapshot.exists() && dataSnapshot.getKey() != currentUserId && !blockingMe(dataSnapshot.getKey()) && !hidingHim(dataSnapshot.getKey()) ){
        //Some code
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}

First Function

private boolean blockingMe(String key) {

    final DatabaseReference MeB = FirebaseDatabase.getInstance().getReference().child(currentUserId).child("blockingUser").child(key);
    final Boolean[] x = new Boolean[1];
    MeB.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                x[0] = true;
            }else{
                x[0] = false;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    return x[0];

}

Second Function

private boolean hidingHim(String key) {

    final DatabaseReference MeB = FirebaseDatabase.getInstance().getReference().child(key).child("hidingUser").child(currentUserId);
    final Boolean[] x = new Boolean[1];
    MeB.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.exists()){
                x[0] = true;
            }else{
                x[0] = false;
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });


    return x[0];

}
  • It is a null pointer exception saying that blockingMe() & hidingHim() functions return nulls. – kakaealmadrid Feb 28 '20 at 18:33
  • 1
    You're trying to return values synchronously that you're altering in asynchronous callbacks. The `return x[0]` happens before `onDataChange()` has returned. You should restructure your code to access data altered by the callbacks only after they've returned. – Sammy T Feb 28 '20 at 23:17
  • Please check the duplicate to see why do you have this behavior and how can you solve this using a custom callback. – Alex Mamo Feb 29 '20 at 04:53

0 Answers0