简体   繁体   中英

How to access data beyond 3 nodes on realtime firebase?

I want to access my list of liked users. This is my database. I want to list these users in the like node with a for loop. (java and android studio)

If you want a list of liked users that correspond to the logged-in user, please use the following lines of code:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
DatabaseReference likeRef = usersRef.child(uid).child("like");
likeRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            for (DataSnapshot likeSnapshot : task.getResult().getChildren()) {
                String likedUid = likeSnapshot.getValue(String.class);
                usersRef.child(likedUid).get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DataSnapshot> task) {
                        if (task.isSuccessful()) {
                            for (DataSnapshot userSnapshot : task.getResult().getChildren()) {
                                String name = userSnapshot.child("nome").getValue(String.class);
                                Log.d("TAG", name);
                            }
                        } else {
                            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
                        }
                    }
                });
            }
        } else {
            Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
        }
    }
});

The result in the logcat will be name of the users that exist within:

Firebase-root -> Users -> $UID -> like

A more convenient way for storing the UIDs might be:

Firebase-root
  |
  --- Users
       |
       --- $UID
            |
            --- like
                 |
                 --- $UID: true
                 |
                 --- $UID: true

See, there is no need for any pushed keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM