Firebase中的2个关键问题

时间:2017-09-26 20:29:39

标签: java android firebase firebase-realtime-database

我正在使用Firebase。

enter image description here

1。问: 我创建了一个密钥:

final String CHATS_CHILD = "chats/" + mFirebaseDatabaseReference.push().getKey();
                mFirebaseDatabaseReference.child(CHATS_CHILD).push().setValue("and so on...");

您在图片中看到的结果。现在我在Firebase中创建了一个带有子项的键,但是如何将键输入到我的Android应用程序中? (我的意思是第一把钥匙,在Chats之后)

2。 Qestion类似

您在我的图片中看到数据库。当我在文本后搜索时,如何在聊天后获取第一个键?因此,例如,我想要一个具有Text" Test1"

作为子项的键

怎么做?

提前致谢。

2 个答案:

答案 0 :(得分:0)

我认为您应该展平您的数据,以便仅使用消息文本获取消息密钥和聊天密钥。您可以将实际消息保存在单独的路径中(例如"消息")并仅将消息密钥保留在相关聊天的路径中,如以下结构所示:

Proposed "chats" path Proposed "messages" path

创建Chat类:

public class Chat {

    private Map<String, Boolean> messageKeys;

    public Chat() {
        // Default constructor required for calls to DataSnapshot.getValue(Chat.class)
    }

    public Chat(Map<String, Boolean> messageKeys) {
        this.messageKeys = messageKeys;
    }

    public Map<String, Boolean> getMessageKeys() {
        return messageKeys;
    }

    public void setMessageKeys(Map<String, Boolean> messageKeys) {
        this.messageKeys = messageKeys;
    }
}

..和Message课程:

public class Message {

    private String chatKey;
    private String text;
    private long time;

    public Message() {
        // Default constructor required for calls to DataSnapshot.getValue(Message.class)
    }

    public Message(String chatKey, String text, long time) {
        this.chatKey = chatKey;
        this.text = text;
        this.time = time;
    }

    public String getChatKey() {
        return chatKey;
    }

    public void setChatKey(String chatKey) {
        this.chatKey = chatKey;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }
}

然后查询消息并查找其文本字段等于您正在搜索的字词的消息,例如&#34; Test1&#34;:

DatabaseReference chatsRef = FirebaseDatabase.getInstance().getReference("chats");
DatabaseReference messagesRef = FirebaseDatabase.getInstance().getReference("messages");

messagesRef.orderByChild("text").equalTo("Test1").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot child : dataSnapshot.getChildren()) {
            String messageKey = child.getKey();
            Message message = child.getValue(Message.class);
            String chatKey = message.getChatKey();
            // Now you have both the chatKey and the messageKey...
        }
    }

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

在这种情况下,创建一个新聊天及其第一条消息如下所示(可以视为对您的第一个问题的回答):

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String chatKey = rootRef.push().getKey();
String messageKey = rootRef.push().getKey();
Message newMessage = new Message(chatKey, "My message trial", Calendar.getInstance().getTimeInMillis());
Map<String, Boolean> messageKeys = new LinkedHashMap<>();
messageKeys.put(messageKey, true);
Chat newChat = new Chat(messageKeys);
rootRef.child("messages").child(messageKey).setValue(newMessage);
rootRef.child("chats").child(chatKey).setValue(newChat);

检索属于已知密钥的聊天的所有邮件:

String chatKey = "chatKey1";   // Get it somehow
DatabaseReference messagesRef = FirebaseDatabase.getInstance().getReference("messages");

messagesRef.orderByChild("chatKey").equalTo(chatKey).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        List<Message> messageList = new ArrayList<>();
        for (DataSnapshot child : dataSnapshot.getChildren()) {
            String messageKey = child.getKey();
            Message message = child.getValue(Message.class);
            messageList.add(message);
        }
        // Now you have all messages in messageList...
    }

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

答案 1 :(得分:0)

除了回答Mehmed之外:Firebase DB不仅支持设置/检索单个字段,还支持整个某些类的对象。 在下面的示例中,我定义了MyChat类,创建了几个对象并将它们放入Firebase DB中。然后我检索所有这些(作为对象,而不仅仅是字符串)并将它们放入ArrayList。

    FirebaseDatabase frDb = FirebaseDatabase.getInstance();
    DatabaseReference mFirebaseDatabaseReference = frDb.getReference();
    final String CHATS_CHILD = "chats/theChat" ; //+ mFirebaseDatabaseReference.push().getKey();

    // Create 3 objects of class MyChat
    MyChat chat1 = new MyChat("Test1", "21-Sep-2017");
    MyChat chat2 = new MyChat("Test21", "26-Sep-2017");
    MyChat chat3 = new MyChat("TestB", "28-Sep-2010");

    //Add all the chats to  Firebase DB
    mFirebaseDatabaseReference.child(CHATS_CHILD).push().setValue(chat1);
    mFirebaseDatabaseReference.child(CHATS_CHILD).push().setValue(chat2);
    mFirebaseDatabaseReference.child(CHATS_CHILD).push().setValue(chat3);


    // Here we will retrieve all the chats and put them to array
    // Declare array to keep results
    final ArrayList<MyChat> arr1 = new ArrayList<MyChat>();

    //Listener
    ChildEventListener chEvLst = mFirebaseDatabaseReference.child("chats").addChildEventListener(new ChildEventListener() {

        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                for (DataSnapshot ds1 : dataSnapshot.getChildren()) {
                    MyChat chatRes = ds1.getValue(MyChat.class);
                    Log.i("Next chat text:",chatRes.getmText());
                    Log.i("Next chat date:",chatRes.getmText());
                    arr1.add(chatRes); // retrieve and save chats to array
                }

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

这是MyChat类

public class MyChat {


String mText = "Test1";       // default values...
String mDate =  "26-Sep-2017";

// *** MUST TO HAVE EMPTY CONSTUCTOR FOR FIREBASE !!! ***
public MyChat() {
}

// Second constructor
public MyChat(String mText, String mDate) {
    this.mText = mText;
    this.mDate = mDate;
}

// *** MUST TO HAVE ALL GETTERS/SETTERS FOR FIREBASE!!! ***
// Getters/setters
public String getmText() {
    return mText;
}

public void setmText(String mText) {
    this.mText = mText;
}

public String getmDate() {
    return mDate;
}

public void setmDate(String mDate) {
    this.mDate = mDate;
}

}

这就是结果DB结构:

enter image description here

祝你好运!