0

When i need assign value from firebase to global variable, it always null.

String idban = "";
DatabaseReference likeRef = FirebaseDatabase.getInstance().getReference().child("Banners");
        likeRef.orderByChild("name")
                .equalTo(name)
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot childSnapshot: dataSnapshot.getChildren())
                        {
                            idban = childSnapshot.getKey();

                        }

                    }
                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
Log.e("IDBAN",idban) // idban == "" when i call it;

Can someone help me solve it. Sorry my English very bad.

  • Move `Log.e("IDBAN",idban) ` inside `onDataChange` .. `ValueEventListener` is a callback of asynchronous call so you need to do all the `DataSnapshot` related code inside `onDataChange`. – ADM Apr 22 '19 at 05:34
  • Please check the duplicate to see why do you have this behaviour and how can you solve this using a custom callback. – Alex Mamo Apr 22 '19 at 09:22
  • Thanks you. So sad because i need use var outside onDataChange – Vân Thiên Apr 22 '19 at 09:48

1 Answers1

0
addListenerForSingleValueEvent 

run in background thread. Before it returns value to your global String, the Log statement gets executed.

That's why it returns null value.

Instead of writing this idban = childSnapshot.getKey(); write a method like Updatevalue(childSnapshot.getKey()); And then define the method as

Private void Updatevalue (String key){
idban = key;
Log.e("IDBAN",idban)
}
Prafulla Nayak
  • 169
  • 1
  • 6