Reputation: 990
I am working on app where I want to show the data only of the users whose contact numbers are saved in the phone. So, I retrieved a list of contact numbers contactList
. Now, I want to get all the contactList
user's post from Firebase. Is there any way I can ask the Firebase for only those nodes in my contactList
. One Way is to retrieve all users and then get relevant users from that (like I did below). Is there any better way to do so ?
Users: {
7828272892 : {
name: xyz,
gender: male,
phoneNo: 7828272892
Posts: {
SomeKey1: {
content: "This is post 1", Var2: "kkk"} }},
7924272894 : {name: abc, gender: male, phoneNo: 7924272894}
}
Code:
databaseReference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
List<Post> allItems = new ArrayList<Post>();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
if (contactList.contains(postSnapshot.child("phoneNo").getValue())) {
// retrieve posts
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Upvotes: 1
Views: 2603
Reputation:
Try this code to read multiple nodes data..
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mDatabase.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user); // add all data into list.
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Upvotes: 1
Reputation: 138824
Is there any way I can ask the firebase for only those nodes in my
contactList
?
Yes, the way in which you already do this.
Is there any better way to do so?
The way in which you do this is a common practice used in Firebase. You query the database and check is the data already exists in the list, in your case in the contactList
. If the list contains that phoneNo
then you can retrieve the posts.
Upvotes: 1