我对 Android 和 Java 还很陌生,我正在尝试自学锁定。
现在,我正在尝试根据已知的 uid
检索用户名,但无法完全弄清楚语法。
我的 Firebase 数据库如下所示
├── chat
│ ├── -M5D96yP5Ac688-ZPU0C << chatId 1
│ │ ├── info
│ │ │ ├── groupName: Breakfast Club
│ │ │ ├── id: -M5D96yP5Ac688-ZPU0C
│ │ │ └── Users:
│ │ │ ├── 8J7PX3ezjMTuOiAPO1BbOGJGP1g1: true
│ │ │ └── QvmGG2vPfTrdjZBfWP2ZotajYE3: true
│ │ └──Messages
│ │ .....
├── user
│ ├── 8J7PX3ezjMTuOiAPO1BbOGJGP1g1 << userId
│ │ ├── chat:
│ │ │ ├── -M5D96yP5Ac688-ZPU0C: true << chatId 1
│ │ │ ├── -M5DQuUsTJwO6tdVUstC: true
│ │ │ └── -M5DQuUsTJwO6tdVUstC: true
│ │ ├── email: JohnBender@bkfastclub.com
│ │ ├── name: John Bender
│ │ └──notificationKey: "28cb76b1-e2cd-4fa6-bf37-38336dafc45a"
│ ├── kLdxJGA7Yyfch1TthnnAPrnyny93
我有我所在的groupId,以及存储的成员的userId
private void getGroupMembers() {
String key = mChatObject.getChatId();
ArrayList<UserObject> mMembers = mChatObject.getUserObjectArrayList();
DatabaseReference chatInfoDb = FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("info").child("users");
DatabaseReference mUserDB = FirebaseDatabase.getInstance().getReference().child("user");
// Query query = mUserDB.orderByChild("uid").equalTo(chatInfoDb.getUid());
}
我只是不太清楚如何搜索用户路径并获取用户的名称并存储它们。
最终我想将它们显示在 RecyclerView
中。
任何帮助将不胜感激。
最佳答案
如果您想获取chat/chatID/info/users
下的用户姓名,请查看我的答案
好吧,如果您的key
实际上是正确的,首先循环遍历chat/chatID/info/users
下的所有子项,然后通过调用User<来获取名称
节点。
像这样:
//chat ID
String key = mChatObject.getChatId();
//database reference (be careful for lower case or upper case names)
DatabaseReference chatInfoDb = FirebaseDatabase.getInstance().getReference().child("chat").child(key).child("info").child("Users");
DatabaseReference mUserDB = FirebaseDatabase.getInstance().getReference().child("user");
//a first call to the `chat` node:
ValueEventListener chatListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//loop through children
for(DataSnapshot ds: dataSnapshot.getChildren()){
//this will run n times, where n is the number of children under chat/chatID/info/Users
String userId = ds.getKey();
//now we grab the name for every userID under chat/chatID/info/Users
mUserDB.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//grab the name and add it to some list
String name = dataSnapshot.child("name").getValue(String.class);
list.add(name)
}
@Override
public void onCancelled(DatabaseError databaseError) {
// log error
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
}//loop end
}
@Override
public void onCancelled(DatabaseError databaseError) {
//log error
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
chatInfoDb.addValueEventListener(chatListener);
关于java - 根据已知的 uid 从 firebase 检索用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61362727/