【问题标题】:How do I check if a child exists in the a branch in the database so that I can return values based on that child如何检查数据库的 a 分支中是否存在子项,以便我可以根据该子项返回值
【发布时间】:2023-04-10 04:48:01
【问题描述】:

UI from using the code i mention 我的数据库是这样设置的:

-Students
    -user1
        -name
        -pass
        -etc...
    -user2

-Admin
    -admin1

我想检查当前用户是管理员还是学生,以便我可以转到数据库中的某个参考

这是我的代码:

    user = FirebaseAuth.getInstance().getCurrentUser();
    reff = FirebaseDatabase.getInstance().getReference().child("Students").child(user.getUid());

    reff.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            name = dataSnapshot.child("name").getValue().toString();
            lastName = dataSnapshot.child("lastName").getValue().toString();
            studentID = dataSnapshot.child("studentID").getValue().toString();
            email = dataSnapshot.child("email").getValue().toString();
            password = dataSnapshot.child("password").getValue().toString();
            confirmPassword = dataSnapshot.child("password").getValue().toString();
            inputStudentID.getEditText().setText(studentID);
            inputName.getEditText().setText(name);
            inputLastName.getEditText().setText(lastName);
            inputEmail.getEditText().setText(email);
            inputPassword.getEditText().setText(password);
            inputConfirmPassword.getEditText().setText(confirmPassword);


        }

为了得到我必须做的学生信息

FirebaseDatabase.getInstance().getReference().child("Students").child(user.getUid());

但是如果我以管理员身份登录,我将如何去那个分支并显示他们的信息。我已经尝试过使用带有

的 if 语句
dataSnapshot.child("Students").hasChild(user.getUID)

参考

FirebaseDatabase.getInstance().getReference()

查看登录的用户是否在学生分支,但没有工作。

UI for both admin and student with the code in picture 3

Code for image 2

【问题讨论】:

  • 您的尝试有什么问题?哪一行代码没有达到你的预期?
  • 这段代码中到底有什么不符合您的预期?也请回复@AlexMamo
  • 没有显示管理员信息,不像学生信息@AlexMamo
  • @AlexMamo 我已添加图片供参考
  • @AlexMamo 我找到了问题的答案。我阅读了您对另一篇文章的其他答案之一,看起来我必须使用回调函数,因为数据是异步的

标签: java android firebase-realtime-database firebase-authentication


【解决方案1】:

为了查看一个子节点是否存在于一个节点的分支中并基于它运行你的代码,你必须使用一个回调函数。

参考this文章

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多