0

In my application I need to retrieve a value from one node in my database and use this value to pass in to another method elsewhere in my code.

Is it possible to read data from the data snapshot in firebase and return this value for use outside of the data snapshot?

For example, to return the phoneNum or groupId variables from the below method for use in another method:

public void getUserPhoneNum(String uId){

    usersDatabase.child(uId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists() || dataSnapshot.getValue() != null) {
                User mUser = dataSnapshot.getValue(User.class);
                String userPhone = mUser.getPhoneNum();

                Group mGroup = dataSnapshot.child("groups").getValue(Group.class);
                String groupId = mGroup.getGroupId();

                groupsDatabase.child(groupId).child("members").child(userPhone).child("playing").setValue()
                if (userPhone != null) {
                }
            }
            else {

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CiarĂ¡nimo
  • 517
  • 1
  • 9
  • 21

2 Answers2

1

This is happening because onDataChange is called asynchronously. This means that the statement in which you get the phoneNum is executed before onDataChange has been called. If you want to use it outside, it will be null. So in order to use the phoneNum, you need to use it inside the onDataChange() method or for or another approach visit this post and this post.

Hope it helps.

Community
  • 1
  • 1
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
0

It is not possible, because when you are using addListenerForSingleValueEvent you are defining a class that implements 'onDataChangeandonCancelled`.

You can instead use an interface to let the class now know when the phone number has been fetched.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dishonered
  • 8,449
  • 9
  • 37
  • 50