在Firebase Android中使用子项键获取父名称

时间:2018-07-05 11:25:16

标签: java android firebase firebase-realtime-database

我正在尝试通过在Android Studio中使用子项“ UID”来获取父级名称“ 170002001”。请帮忙。在此先感谢:)

enter image description here     字符串uid = user.getUid();

private void getdata(){
    DatabaseReference reference;
    reference = FirebaseDatabase.getInstance().getReference();
    reference.orderByChild("UID").equalTo(uid).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                keys = childSnapshot.getKey();
                status.setText(keys);
            }
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

编辑: 除“ 170002001”外,我能够检索所有父名称。 :(

1 个答案:

答案 0 :(得分:2)

将其放入您的onDataChange(DataSnapshot dataSnapshot)监听器中

String parent = dataSnapshot.getKey();

由于firebase会为此管理一个可能的父键列表,所以请执行此操作

DatabaseReference reference;
reference = FirebaseDatabase.getInstance.getReference();

reference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            String parent = childSnapshot.getKey();
            Log.i(TAG,parent);
        }
    }

请注意,此处的引用将是您的"170002001"键上方的节点,该键是所有这些键的父级

编辑:如果要在每个节点中获取所有UID,请执行以下操作

创建一个POJO类来保存该用户ID

public class UserPojo {


    private String UID;

    public UserPojo(String UID) {
        this.UID = UID;
    }
    public UserPojo() {
    }


    public String getUID() {
        return UID;
    }

    public void setUID(String UID) {
        this.UID = UID;
    }


}

然后像上面一样做

   reference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                String parent = childSnapshot.getKey();
                  UserPojo user = childSnapshot.getValue(UserPojo.class);
//get your User ID
 String user = user.getUID();
                Log.i(TAG,parent);
            }
        }