I have a root node named 'Posts'. Then each node inside Posts has a unique postID generated by push(). Now each post has several children. One such child is "saves" in which I have stored the userIDs of those users who have saved this particular post. What I want to do is that I want to create and display a list of all those posts which a particular user has saved.
This means that I have to write a code that will scroll through all posts in 'Posts' node, check for 'saves' child in each post, if it exists, then check for userID of a particular user in 'saves', if it exists, then that post should be added to a list called 'mySavedPosts'.
Please click here to see the structure of my 'Posts' node.
I have tried many different ways to achieve this but I am just getting an empty list or app crashes. I cannot post all the different ways that I have tried since that would make this question very lengthy and clumsy, but all my ways revolve somewhere around this approach:
FirebaseDatabase.getInstance().getReference()
.child("Posts")
.child("saves")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
mySavedPosts.clear();
if (snapshot.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).exists()){
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
Post post = dataSnapshot.getValue(Post.class);
mySavedPosts.add(post);
}
}
Collections.reverse(mySavedPosts);
postAdapterSaves.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
I have also tried entering .child(post.getPostID()) after .child("Posts") but that generates a null Pointer Exception. I have also tried entering .child(auth.getUid()) after .child("saves"), that didn't work too! I have tried 10s of other modifications but none of them have worked.
CodePudding user response:
According to your comment:
I just need to see if the auth.getUid() is there in the children of "saves".
To check if the UID of the authenticated user exists in the "saves" node, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference postsRef = rootRef.child("Posts");
Query query = postsRef.orderByChild("saves/" uid).equalTo(true);
query.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
@Override
public void onComplete(@NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot postSnapshot : task.getResult().getChildren()) {
Post post = postSnapshot.getValue(Post.class);
mySavedPosts.add(post);
}
Collections.reverse(mySavedPosts);
postAdapterSaves.notifyDataSetChanged();
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});