unipin
unipin

Reputation: 309

Get last child for each child using Firebase Database

I want to get sender_uid values on the image below:

enter image description here

This is my code below. I don't get any values with it, and I don't know why. Can someone explain what is wrong with the code? Thanks!

EDIT: I only want the last sender_uid for each parent - for example:

Upvotes: 0

Views: 678

Answers (2)

Alex Mamo
Alex Mamo

Reputation: 138824

Assuming that the chat node is a direct child of your Firebase root, to solve this, please use the following query:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef
    .child("chat")
    .child(receiver_id + "_" + sender_uid)
    .orderByChild("sender_uid")
    .limitToLast(1);
query.addListenerForSingleValueEvent(/* ... */);

Upvotes: 0

Gastón Saillén
Gastón Saillén

Reputation: 13129

You can do it this way to get the sender_uid from each node

First create a pojo class to get your desired data

public class UserPojo {

    private String sender_uid;

    public UserPojo() {

    }

    public String getSender_uid() {
        return sender_uid;
    }

    public void setSender_uid(String sender_uid) {
        this.sender_uid = sender_uid;
    }
}

and then just retrieve it for each chat ref

mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                List<UsersListGetter> usersList = new ArrayList<>();
                recyclerView.setAdapter(new UsersListAdapter(usersList, getApplicationContext()));

                recyclerView.setAdapter(new UsersListAdapter(null, getApplicationContext()));

                for (DataSnapshot ch : dataSnapshot.getChildren()) {
                  UserPojo up = ch.getValue(UserPojo.class);
                  String senderUid = up.getSender_uid(); //here you got your sender_uid

                        Query lastQuery = mDatabase.child(ch.getKey()).orderByKey().limitToLast(1);
                        lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                String message = dataSnapshot.child("message_body").getValue().toString();
                                Log.d("MSG", message);
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                                //Handle possible errors.
                            }
                        });

                }
            }

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

        }
    });

Upvotes: 1

Related Questions