Java – Get references and keys in the custom object Firebase Android

Get references and keys in the custom object Firebase Android… here is a solution to the problem.

Get references and keys in the custom object Firebase Android

I want to pass the dataSnapshot and key references for each specific object into the custom Message object.

I’ve tried using the key “String key” in Message.class, but it seems to return null.

This is what my Message object looks like at present:

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 do I properly pass the dataSnapshot.getKey() string to a custom object? I don’t see examples on the Firebase documentation, and to be clear, I was using “legacy Firebase” before they were updated.


When you get an instance of Message from a DataSnapshot, you might be doing:

Message message = snapshot.getValue(Message.class)

Since this starts with getValue(), the message will not contain the key for the DataSnapshot.

You can set the key:, after reading the message

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

In this case, you need to mark getKey() as @JsonIgnore to ensure that Jackson tries to autofill or serialize it.

Related Problems and Solutions