0

I'm trying to get the value of a variable that's in an inner class , which was override by firebase "addValueEventListener" , but when I try to print out the value outside these methods I always get "NULL". This is my code:

DatabaseReference reff = database.getReference().child("Users").child(userId);

                    reff.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            User r= dataSnapshot.getValue(User.class);
                           username= r.getUserN();

//when I try to print out the value of username here it shows up

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });
                    DatabaseReference ref = database.getReference().child("service").child(b);
                    ref.addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            Service s = dataSnapshot.getValue(Service.class);

                            servicename=s.getNomservice();

//same thing as username , i get the value

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });

                    rv = new Rv(username,servicename,dt,tm);
                    RVId = myRef.push().getKey();
                    myRef.child(RVId).setValue(rv);

//and here when I print out username and servicename , I get null

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Alia Al-Nighaoui
  • 135
  • 1
  • 1
  • 8

1 Answers1

0

You cannot use something now that hasn't been loaded yet. With other words, you cannot simply use the username outside the onDataChange() method because it will always be null due the asynchronous behaviour of this method. This means that by the time you are trying to print that result outside that method, the data hasn't finished loading yet from the database and that's why is not accessible.

A quick solve for this problem would be to use that results only inside the onDataChange() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193