我尝试将聊天功能添加到以Firebase Realtime DB作为存储空间的Android应用中。
我的架构是这样的,
conversation: {
conversation_id_generated_by_firebase: {
last_message: {
message: "hehe"
type: "text"
attachments: {0: "url", 1: "url"}
likes: {0: "uid1", 1: "uid2"}
created_at: 1245789898
},
messages: {
m1: {
message: "hehe"
type: "text"
attachments: {0: "url", 1: "url"}
likes: {0: "uid1", 1: "uid2"}
created_at: 1245789898
}, m2: {}, m3: {}, m4: {}
},
read_till: {
uid1: 14567894229
uid2: 14567894228
},
created_at: 1456789329
updated_at: 1456789429
},
}
现在,如何在一个查询/调用中使用ID获取多个会话?
答案 0 :(得分:2)
没有Firebase等同于SQL的SELECT * WHERE id IN (1,2,3)
。在Firebase中,您将分别检索每个项目。
这并不像大多数开发人员想象的那么慢,因为Firebase可以通过单个连接有效地管理此类请求。请参阅我的答案,以获得更长的解释(以及一些ASCII艺术):Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly
答案 1 :(得分:0)
通过检索ID,您是否想要检索" conversation_id_generated_by_firebase",如果是,我已经实现了一些类似的事情,根据您的数据库详细信息修改了代码。如果您可以提供一些您尝试过的代码,我可以帮助您。
ArrayList<String> keyList = new ArrayList<>();
// i am assuming you have Chat Object for each conversation
ArrayList<Chat> chatList = new ArrayList<>();
myRef = database.getReference().child("conversation");
ValueEventListener chatListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//will be called every time a new conversation is added
if(dataSnapshot != null){
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String key = postSnapshot.getKey();
//store key(your id) in array list
keyList.add(key);
//now i am assuming you have an object of chat message
Chat chat = postSnapshot.getValue(Chat.class);
//add all conversation to chatList ArrayList
chatList.add(chat);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
//handle error incase something fails
}
};
myRef.addValueEventListener(chatListener);