0
//It is in a loop
flag=false;
DataRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot snapshot1) {
        for (DataSnapshot snapshot2 : snapshot1.getChildren()) {
            Book book = snapshot2.getValue(Book.class);
            if((key).equals(book.getTable())){
                flag=true;
            }
        }
        
        //work correctly
        System.out.println(flag);
    }
    @Override
    public void onCancelled(@NonNull DatabaseError error1) {
    }
});

//not work correctly
System.out.println(flag);

//end of loop

The variable flag; is not accessed outside the addValueEventListener as wanted.

Outside of the addValueEventListener, I want to access the variable.

  • There is no way you can do that. Firebase API is asynchronous. So please check the duplicate to see how can you solve this using a callback. You might also be interested in reading this [resource](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5). – Alex Mamo Feb 04 '23 at 09:50

0 Answers0