TUSHAR
TUSHAR

Reputation: 327

want to put limit in list at time of retrieving data from firebase

    public class FriendModel {

    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("userid")
    @Expose
    private String userid;
    @SerializedName("photourl")
    @Expose
    private String photourl;
    @SerializedName("messages")
    @Expose
    private List<Message> messages = null;
}

I am using firebaserecycler adapter that populates FriendModel in a list.

In each object of the FriendModel list, I have another list which is List of Message. What I want is to get the last item of this Message list.I have to show the last item in my same adapter. Is there any way to add this limitation to my List. My List of Message can be very long can contains tons of items so I don't want to hold all objects in my Message list that's why I need to do this. Any help would be appreciated...

Upvotes: 3

Views: 247

Answers (4)

Seenu69
Seenu69

Reputation: 1054

There is no method or API in firebase that fetches the only custom number of items from a list inside a model class.

You have to get all the messages and store it locally in list variable. If you want to show only last message use the following code in onBindViewHolder method of the recyclerview adapter class -

@Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {

        FriendModel frdModelObj = frdModelList.get(position);
        List<Message> messagesList = frdModelObj.getMessages();
        String lastMessage = messagesList.get(messagesList.size()-1);
}

Upvotes: 0

Mehmed
Mehmed

Reputation: 3040

Firebase will retrieve all those messages even you do some local tricks to store only the last N messages in the list. Therefore you need to change your structure and flatten your data. Only the message ids/keys should be stored in a list in your FriendModel. This way, you will be avoiding the overhead of retrieving all the messages, however, you have to make another call to get the last message itself.

For the solution I mention, you can update your database as follows:

Proposed "friends" path

Proposed "messages" path

Then you should update your FriendModel class like this:

public class FriendModel {

    @SerializedName("email")
    @Expose
    private String email;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("userid")
    @Expose
    private String userid;
    @SerializedName("photourl")
    @Expose
    private String photourl;
    @SerializedName("messages")
    @Expose
    private Map<String, Boolean> messages;

    // Getters and setters...

    @Exclude
    public String getLastMessageKey() {
        if (messages != null) {
            SortedSet<String> keys = new TreeSet<>(messages.keySet());
            return keys.last();
        } else {
            return null;
        }
    }
}

Then to retrieve friend and the last message, you can do as follows:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("friends").child("1111111111");
ref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        FriendModel friend = dataSnapshot.getValue(FriendModel.class);
        String lastMessageKey = friend.getLastMessageKey();

        if (lastMessageKey != null) {
            FirebaseDatabase.getInstance().getReference("messages").child(lastMessageKey)
                .addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    MessageModel lastMessage = dataSnapshot.getValue(MessageModel.class);
                    // Now you have the last message.
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    throw databaseError.toException();
                }
            });
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

Upvotes: 0

Abhishek
Abhishek

Reputation: 1261

In that case I would suggest you define a separate class for "messages". So hold all user data in 'FriendModel' class and store all messages in a class called 'Messages'. In your firebase database store the messages against a specific FriendModel.userid. That way you can retrieve the list of messages separately from the FriendModel. And when retrieving the list of messages use the 'limitToLast' constraint to retrieve only 1 message like in the example below

Query recentMessageQuery = databaseReference.child(userid).child("messages").limitToLast(1);

Please let me know if you need a more detailed explanation. But this should get you started -> https://firebase.google.com/docs/database/android/lists-of-data

Upvotes: 1

Alex Mamo
Alex Mamo

Reputation: 138979

I suggest you to use this method that returns the last element of your messages list.

static Message getLastMessage(List<Message> list) {
    int listSize = list.size();
    return list.get(listSize-1);
}

Upvotes: 0

Related Questions