0

I'm building an Android app that uses Firebase database and I need DataSnapshot a lot in the app so I decided to make a helper method to get me the DataSnapshot and here how I managed to implement it inside a Helper class that I created:

static FirebaseDatabase database = FirebaseDatabase.getInstance();
static DatabaseReference playersReference =  database.getReference().child("players");
static DataSnapshot snapshot;

public static DataSnapshot getDataSnapshot(){

        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                snapshot = dataSnapshot;
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
            }
        };

        playersReference.addListenerForSingleValueEvent(valueEventListener);

        return snapshot;

    }

But whenever I try to use the method it returns null, any help?

Ahmed Nabil
  • 581
  • 1
  • 7
  • 26

3 Answers3

1

First, Create a separate helper class which breaks up the static calls to the database such as the following:

public class FirebaseDbRef {

    private static DatabaseReference ref; 

    private static DatabaseReference getFirebaseDatabase() {
        if (ref == null) 
            ref = FirebaseDatabase.getInstance().getReference();
        return ref;
    }

    public static DatabaseReference getPlayerRef() {
        return getFirebaseDatabase().child("player");
    }

}

Then in your activity/fragment, call the method and add a listener to retrieve the snapshot:

FirebaseDbRef.getPlayerRef().addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            //USE SNAPSHOT
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            databaseError.getMessage();
        }
    });

Make sure your pathing is correct to access the proper snapshot. You can always Log to verify.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

The getDataSnapshot() does three things:

  1. Creates a listener
  2. Registers the listener
  3. Returns snapshot

Note that none of these steps sets the value of snapshot. You are setting it in one of the listener's methods which is not called until after getDataSnapshot() returns.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

You cannot return something that hasn't been loaded yet. onDataChange() method is called asynchronous which means that is called even before you are getting the DataSnapshot object from the database. For more details you can see my answer from this post.

If you want to use the DataSnapshot object outside onDataChange() method you need to create your own callback as explained at the end on that answer.

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