I'm trying to figure out a way of retrieving all users that follow me. Let's say I'm user1, and user2 and user3 are my followers. How can I only retrieve them instead of retrieving all users and filter them on the client side?
This is how my structure looks like:
{
"followers" : {
"user1" : {
"user2" : true,
"user3" : true
}
},
"following" : {
"user2" : {
"user1" : true
},
"user3" : {
"user1" : true
}
},
"users" : {
"user1" : {
"firstName" : "User One"
},
"user2" : {
"firstName" : "User Two"
},
"user3" : {
"firstName" : "User Three"
}
}
}
I don't have any code yet because I don't know how to even start. Any help is appreciated. Thanks for reading.
EDIT: This is how I got it working. I don't know if it's the best option, but it works for now.
ChildEventListener childEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
// A new comment has been added, add it to the displayed list
String uid = dataSnapshot.getKey();
mDatabase.child("users").child(uid).addListenerForSingleValueEvent(
new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Get user value
User user = dataSnapshot.getValue(User.class);
users.add(user);
notifyDataSetChanged();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "getUser:onCancelled", databaseError.toException());
}
});
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildChanged:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so displayed the changed comment.
//Comment newComment = dataSnapshot.getValue(Comment.class);
String commentKey = dataSnapshot.getKey();
System.out.println("Changed: "+commentKey);
notifyDataSetChanged();
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Log.d(TAG, "onChildRemoved:" + dataSnapshot.getKey());
// A comment has changed, use the key to determine if we are displaying this
// comment and if so remove it.
String commentKey = dataSnapshot.getKey();
System.out.println("Removed: "+commentKey);
notifyDataSetChanged();
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousChildName) {
Log.d(TAG, "onChildMoved:" + dataSnapshot.getKey());
// A comment has changed position, use the key to determine if we are
// displaying this comment and if so move it.
//User user = dataSnapshot.getValue(User.class);
String commentKey = dataSnapshot.getKey();
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "postComments:onCancelled", databaseError.toException());
Toast.makeText(context, "Failed to retrieve followers.", Toast.LENGTH_SHORT).show();
}
};
mDatabase.child("followers").child(currentUser.getUid()).addChildEventListener(childEventListener);