Reputation: 103
I've created a ListView where it should display all the usernames of the firebase users that exists. But now ive got the problem that i dont know how to get the child of the userID's. Sure i can create an array with the ids in the database but if more people register on the app it dont do it automaticly. So do you know how to get all childs from a child? It looks like this
Root
iadf09f08asd0fasd
Infos
Username: LeagueHans
i297f9pb2f92
Infos
Username: Julian
08bfbüqw0efü
Infos
Username: Markus
From comments:
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
root.child("Users").child(What to write here).child("Infos").child("Username");
I dont know how to get the the userid(iadf09f08asd0fasd
) as a child.
Upvotes: 2
Views: 1154
Reputation: 599081
When you run a query on a location, you will get a subset of the nodes immediately under that location. You cannot retrieve lower-level children under that.
So either you will have to retrieve all data and then just handle the user name client-side or (preferably) you'll need to change your data model to fit better with your use-case.
root.child("Users").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
String username = snapshot.child("Infos/Username).getValue(String.class);
}
...
This will work, but means that you're retrieving more data than you need. This is one of the many reasons that Firebase recommends that you don't nest data unless you always need it in combination.
The alternative is to:
I often recommend that in Firebase you model the screens of your app. So if you want to show a list of user names in your app, you should keep a list of user names in your database:
Usernames
iadf09f08asd0fasd: "LeagueHans"
i297f9pb2f92: "Julian"
08bfbüqw0efü: "Markus"
Now you can get just the user names with:
root.child("Usernamess").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot snapshot, String previousChildName) {
String username = snapshot.getValue(String.class);
}
...
Upvotes: 2
Reputation: 5865
Try like this...
The firebase addValueEventListener
will get trigger at every time whenever your database get changed so use this to retrieve your data.
mReference.child("Root").child("Infos").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
YourModel mModel = eventSnapshot.getValue(YourModel.class);
Log.e("NAME " ,""+ mModel);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Upvotes: 0