user124532053452
user124532053452

Reputation: 5

How to get all children in firebase

After adding the values to database of firebase like that:

writeNewUser("0",name , "0", "1" );
 writeNewUser("1",name , "0", "2" );
 writeNewUser("2",name , "0", "3" );
 writeNewUser("3",name , "0", "4" );

private void writeNewUser(String GameID, String name, String wpm , String userID) {
        User user = new User(name, wpm , userID );

        mDatabase.child("games").child(GameID).setValue(user);
    }

    @IgnoreExtraProperties
    public class User {

        public String name;
        public String wpm;
        public String userID;

        public User() {
            // Default constructor required for calls to DataSnapshot.getValue(User.class)
        }

        public User(String name, String wpm , String userID) {
            this.name = name;
            this.wpm = wpm;
            this.userID = userID;
        }

    }

And example of how it looks like in firebase: Games > 0 > Name: , WPM: , ID: Games > 1 > Name: , WPM: , ID:

What i want to receive is the from the database are the GameID's sorted from low to high

I would be glad to get some help since I'm new to this database and been searching for few hours already.

Upvotes: 0

Views: 518

Answers (1)

Venkata Narayana
Venkata Narayana

Reputation: 1697

Here's the code to get all the games in the database ordered by key(GameID) assuming you don't need realtime updates.

    final HashMap<Long,User> userMap = new HashMap<>();
    FirebaseDatabase.getInstance().getReference("games").orderByKey().addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Iterable<DataSnapshot> snapshotIterable = dataSnapshot.getChildren();

            for (DataSnapshot aSnapshotIterable : snapshotIterable) {
                userMap.put(Long.parseLong(aSnapshotIterable.getKey()),aSnapshotIterable.getValue(User.class));
            }
          Set<Long> gameIds = userMap.keySet();
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Upvotes: 1

Related Questions