Reputation:
How can get the child values from the Firebase Realtime Database?
Below is my architecture:
Posts
|--firebase key
|--title: test1
|--sub: NY
|--country: USA
--firebase key
|--title: test2
|--sub: DC
|--country: USA
--firebase key
|--title: test3
|--sub: DC
|--country: USA
--firebase key
|--title: test4
|--sub: FRA
|--country: EU
--firebase key
|--title: test5
|--sub: UK
|--country: EU
I want to read the value of sub, but there are a total of three values like DC, but I only want to fetch it once, because what I want to achieve is that states with a value will be displayed in the RecyclerView, but like AL, AZ, AL, AR and so on, it hasn't been added yet, so it won't be displayed.
So how can I do it?
I will use this methods to get post country, so how can show the subs?
DatabaseReference countryRef = FirebaseDatabase.getInstance().getReference("Posts");
Query query = countryRef.orderByChild("country").equalTo(country);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
Upvotes: 1
Views: 297
Reputation: 139039
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("Posts");
postsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
List<String> posts = new ArrayList<>();
for (DataSnapshot ds : task.getResult().getChildren()) {
String sub = ds.child("sub").getValue(String.class);
if(!posts.contains(sub)) {
posts.add(sub);
}
}
for (String post : posts) {
Log.d("TAG", post);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
NY
DC
AK
If you want to display those results in a RecyclerView in Android, you should consider using my answer from the following post:
Upvotes: 0
Reputation: 1
First take a database reference using this code
private DatabaseRefrence mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
You can Simply get child using this code
mFirstChild = mDatabase.child("child-name");
mSecondChild = mFirstChild.child("2-child-name");
Upvotes: 0