Skip to content Skip to sidebar Skip to footer

Obtaining The Reference And Key In Custom Object Firebase Android

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

Solution 1:

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.

Solution 2:

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

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

    return msg;
}

Post a Comment for "Obtaining The Reference And Key In Custom Object Firebase Android"