theBrainyGeek
theBrainyGeek

Reputation: 584

Can't read Firebase Database

This is my code for reading Firebase data:

final String[] booknum = {"0"};
    databaseReference.child("All BID").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {
            booknum[0] =Long.toString(snapshot.getChildrenCount());
            Toast.makeText(getApplicationContext(), booknum[0],Toast.LENGTH_LONG).show();

        }
        @Override public void onCancelled(DatabaseError databaseError) {
            Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
        }
    });
    Toast.makeText(getApplicationContext(), booknum[0],Toast.LENGTH_LONG).show();

When I am executing this, the first toast(inside ValueEventListener) prints the right answer (eg '8'). But the toast outside always prints 0 no matter what.

Please Help!

Upvotes: 3

Views: 884

Answers (1)

Pat Myron
Pat Myron

Reputation: 4648

The ValueEventListener is asynchronous. The lines of code inside of the listener, including the assignment of booknum[0], are not guaranteed to execute before the lines of code written outside of the listener. If you depend on the new value of booknum[0] for some operation, consider moving that operation inside of onDataChange() to ensure it uses the new value.

Upvotes: 1

Related Questions