首页 > 解决方案 > How to access Firebase key node all children when parent node is also a key in hierarchy

问题描述

I trying to access UserInfo, I've stored in Firebase Realtime Database with Database Reference like this Notification -> SenderUserId -> ReceiverUserId.

Please Check the image I want to access all children of ReceiverId Node As I am new the picture won't appear there is a link only: Link to screenshot so that you guys can understand clearly

I try some answer but it didn't work for me. 1) Link to the answer

2)Link to second answer

3)Link to 3rd answer

How I am storing this data:

private void AllNotificationInfo()
    {
        Calendar calForDate = Calendar.getInstance();
        SimpleDateFormat currentDate = new SimpleDateFormat("dd-MMMM-yyyy");
        saveCurrentDate = currentDate.format(calForDate.getTime());


        Calendar calForTime = Calendar.getInstance();
        SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm");
        saveCurrentTime = currentTime.format(calForTime.getTime());

        UsersRef.child(SenderUserId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
             if (dataSnapshot.exists())
             {
                 String  userprofileImage = dataSnapshot.child("profileimage").getValue().toString();
                 String fullname = dataSnapshot.child("Full_Name").getValue().toString();

                 HashMap postsMap = new HashMap( );

                 postsMap.put("time", saveCurrentTime);
                 postsMap.put("date", saveCurrentDate);
                 postsMap.put("profileimage", userprofileImage);
                 postsMap.put("fullname", fullname);

                 NotificationRef.child(SenderUserId).child(ReceiverUserId).updateChildren(postsMap)
                         .addOnCompleteListener(new OnCompleteListener() {
                             @Override
                             public void onComplete(@NonNull Task task) {
                                 if (task.isSuccessful()){

                                     Toast.makeText(PersonProfileActivity.this, "Friend Request Sent!", Toast.LENGTH_SHORT).show();

                                 }
                                 else
                                 {
                                     String message = task.getException().getMessage();
                                     Toast.makeText(PersonProfileActivity.this, "Error! "+message, Toast.LENGTH_SHORT).show();

                                 }
                             }
                         });
             }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

    }

The data is stored properly. No issue but I can't retrieve my data

and I am storing data in one activity and retrieving in another activity.

This is how I tried to retrieve the Info:

public class NotificationsActivity extends AppCompatActivity {

    private Toolbar NotificationToolbar;

    private RecyclerView RnotificationList;
    private DatabaseReference NotificationRef, UsersRef;
    private FirebaseAuth mAuth;
    private String notification_sender_id,CurrentUserId;
    List<String> NKeyList;
    List<NotificationModel> NotificationList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notifications);

        mAuth = FirebaseAuth.getInstance();
        CurrentUserId = mAuth.getCurrentUser().getUid();

        NotificationToolbar = (Toolbar) findViewById(R.id.notification_toolbar_layout);
        setSupportActionBar(NotificationToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setTitle("Notifications");

        RnotificationList = (RecyclerView) findViewById(R.id.notification_list);

        RnotificationList.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);
        RnotificationList.setLayoutManager(linearLayoutManager);

        NotificationRef = FirebaseDatabase.getInstance().getReference().child("Notifications");

        NKeyList = new ArrayList<>();
        NotificationList = new ArrayList<>();

        NotificationRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                {
                    for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
                    {
                        NKeyList.add(dataSnapshot1.getKey());
// Here I am getting the senderKey and converting into a string, I tried one only at index 0 for testing.
//then I am passing the key to a method where I am using this key for DatabaseReference.
                        String key = NKeyList.get(0);
                        GettingRequestSenderInfo(key);
                }

            }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });





    }

    private void GettingRequestSenderInfo(final String key) {

        DatabaseReference ReqSenderRef = FirebaseDatabase.getInstance().getReference().child("Notifications")
                .child(key).child(CurrentUserId);


 //Here above "key" is SenderUserId and CurrentuserId is ReceiverUserId
        ReqSenderRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                {
                    for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
                    {
                        NotificationModel model = dataSnapshot1.getValue(NotificationModel.class);
                        NotificationList.add(model);
                    }

                    NotificationAdapter notificationAdapter1 = new NotificationAdapter(NotificationsActivity.this, NotificationList, NKeyList);
                    RnotificationList.setAdapter(notificationAdapter1);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }
}

But I am getting NotificationList empty. there is no value... I am using RecyclerView, there is one Model Class and Adapter Class if necessary I'll include both classes.But I am getting Null NotificationList All I want to access the data showed in the image above please check.

标签: androidfirebasefirebase-realtime-database

解决方案


我认为保存的节点必须是这样的Notfications/ReceiverID/SenderID

NotificationRef.child(ReceiverUserId).child(SenderUserId).updateChildren(postsMap)
.addOnCompleteListener(new OnCompleteListener() {

..............
..............

现在在NotificationsActivity

确保正确读取 ref:

NotificationRef =FirebaseDatabase.getInstance().getReference().child("Notifications").child(CurrentUserId);

推荐阅读