在Custom Object Firebase Android中获取参考和密钥 [英] Obtaining the reference and key in Custom Object Firebase Android

查看:117
本文介绍了在Custom Object Firebase Android中获取参考和密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望将每个特定对象的dataSnapshot和key的引用传递给自定义的Message对象。

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

我尝试过使用密钥Message.class中的'String key'但它似乎返回null。

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

以下是我的Message对象的当前状态:

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; }

}

任何想法,我如何正确传递dataSnapshot.getKey ()自定义对象的字符串?我没有在Firebase文档中看到一个示例,并且在更新之前要清楚我正在使用旧版Firebase。

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.

推荐答案

当您从 DataSnapshot 获得消息实例时,您可能会这样做:

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

Message message = snapshot.getValue(Message.class)

由于这是从 getValue()开始的,因此该消息将不包含 DataSnapshot的密钥

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

您可以做的是在阅读消息后自己设置密钥

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

您需要标记 getKey() as @JsonIgnore 在这种情况下,确保Jackson尝试自动填充或序列化它。

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

这篇关于在Custom Object Firebase Android中获取参考和密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆