Working on an Android app that is using the new Firebase Database framework. It has data objects that are modeled like this:
Where the Top parent (1234-4321) is the 'chat room', the data object are the 'chat messages', and the numbered items (0, 1, 2) are the 'individual message'.
我可以毫无困难地获取整个数据库并通过侦听器读取它:
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference();
myRef.addChildEventListener(this);
myRef.addValueEventListener(this);
我能够以这种方式得到一个独生子:
FirebaseDatabase database = FirebaseDatabase.getInstance();
String id = "1234-4321";
DatabaseReference myRef = database.getReference().child(id);
myRef.addChildEventListener(this);
myRef.addValueEventListener(this);
但我一生都无法弄清楚如何获取同一类型的多个对象。我的意思是,用户将能够获得多个聊天室(IE,“1234-4321”和“1234-4432”),但我认为做到这一点的唯一方法是:
1) 循环 onChildAdded 或 onDataChange 侦听器,通过匹配 String id 分离出项目并更新它们。然而,这是极其低效的,因为我正在解析整个数据库,该数据库可能非常大
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if(dataSnapshot != null){
try {
ChatObjectV2 objectV2 = (ChatObjectV2) dataSnapshot.getValue();
//Check here for ids and loop through everything
} catch (Exception e){
e.printStackTrace();
}
}
}
or
2)要添加一个特定的子对象,但如果我尝试添加更多的子对象,当我希望它“更宽”时,它会“更深”地进入嵌套对象。
//This won't work because it is going 'deeper' instead of 'wider'
String id = "1234-4321";
String id2 = "1234-4432";
Query myQuery = myRef.child(id).child(id2);
然后以相同的方式在侦听器中循环,但是,我需要为每个聊天室创建一个不同的 DatabaseReference,这是非常低效的。
看起来解决方案可能是使用filters https://firebase.google.com/docs/database/android/retrieve-data#filtering_data,但我一生都无法弄清楚如何在现有的 FirebaseDatabase 和 DatabaseReference 对象中利用它们。有谁知道如何使过滤器适用于我在此处列出的数据模式/模型?
谢谢您的帮助!