4

I'm looking to pass the reference of the dataSnapshot and key of each specific object into a custom 'Message' object.

I've tried using the key 'String key' within the Message.class but it appears to come back null.

Here is how my Message object currently is:

public class Message {

    private String key;
    private String sender_id;
    private String sender_username;
    private String receiver_username;
    private String receiver_id;
    private String chat_id;
    private String message;
    private Firebase ref;
    private double createdAt;
    private boolean read;

    public Message() {
        // empty default constructor, necessary for Firebase to be able to deserialize messages
    }

    public String getKey() { return key; }
    public String getSender_id() { return sender_id; }
    public String getSender_username() { return sender_username; }
    public String getReceiver_username() { return receiver_username; }
    public String getReceiver_id() { return receiver_id; }
    public String getChat_id() { return chat_id; }
    public String getMessage() { return message; }
    public Firebase getRef() { return ref; }
    public double getCreatedAt() { return createdAt; }
    public boolean getRead() { return read; }

}

Any ideas, how I properly pass the dataSnapshot.getKey() String to the custom object? I don't see an example on the Firebase docs, and to be clear I'm using the "legacy Firebase", before they updated.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Jamie22
  • 424
  • 4
  • 15

2 Answers2

6

When you get a Message instance from a DataSnapshot, you are likely doing:

Message message = snapshot.getValue(Message.class)

Since this is starting from getValue(), the message will not contain the key of the DataSnapshot.

What you can do is set the key yourself after reading the Message:

Message message = snapshot.getValue(Message.class);
message.setKey(snapshot.getKey());

You'll want to mark the getKey() as @JsonIgnore in that case, to ensure that Jackson tries to auto-populate or serialize it.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
1

I ended up adding a static method to create the object from the DataSnapshot:

public static Message FromSnapshot(DataSnapshot snapshot)
{
    Message msg = snapshot.getValue(Message.class);
    msg.setKey(snapshot.getKey());

    return msg;
}
Ryan Burns
  • 11
  • 1