【问题标题】:How to retrieve specifics a firebase database entry?如何检索firebase数据库条目的细节?
【发布时间】:2017-06-05 18:53:08
【问题描述】:

我一直在尝试从存储在 firebase 实时数据库中的数据中检索数据字段,但我被卡住了。

这是我的数据库的样子:

这是我在 AuthStateListener 对象中调用的方法,定义如下:

private void alterTextView(final String id) {
    if(id!=null) {
        mDatabase.child("Users").child(id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    if (ds.exists()) {
                        UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
                        String name = userInformation.getName();
                        mWelcomeUserMessage.setText(name);
                        //logging name
                        Log.d("My activity", "name of user with userID - " + id + " is : " + userInformation.getName());
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
}

对这个函数的调用是这样的:

 mAuthStatelistener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            //if user is logged in, the sign_in and sign_up buttons should not be displayed
            if (firebaseAuth.getCurrentUser() != null) {
                userId = firebaseAuth.getCurrentUser().getUid();
                Log.d("Main Activity", "Current userId : " + userId);
                alterTextView(userId);
                mLogInButton.setVisibility(View.INVISIBLE);
                mSignUpButton.setVisibility(View.INVISIBLE);
                //getUserName(firebaseAuth.getCurrentUser().getUid());
                mLogOutButton.setVisibility(View.VISIBLE);
            } else {
                mLogInButton.setVisibility(View.VISIBLE);
                mSignUpButton.setVisibility(View.VISIBLE);
                mWelcomeUserMessage.setVisibility(View.GONE);
                mLogOutButton.setVisibility(View.GONE);
            }
        }
    };

由于某种原因,我在存储来自 userInformation 对象的名称的行的第一个代码摘录中不断收到空指针异常 -

String name = userInformation.getName();

我就是不明白为什么会这样。

我的主要目标是在他/她登录后打印出登录用户的姓名。

有人知道怎么做吗?

更新 1 这是我的 UserInformation 类的样子:

public class UserInformation {

private String name;
private String student_number;
private String faculty;
private boolean isAdmin;

public String getName() {
    return name;
}

public String getStudent_number() {
    return student_number;
}

public String getFaculty() {
    return faculty;
}

public void setName(String name) {
    this.name = name;
}

public boolean isAdmin() {
    return isAdmin;
}

public void setAdmin(boolean admin) {
    isAdmin = admin;
}

public void setStudent_number(String student_number) {
    this.student_number = student_number;
}

public void setFaculty(String faculty) {
    this.faculty = faculty;
}
}

【问题讨论】:

    标签: android firebase firebase-realtime-database


    【解决方案1】:

    不需要onDataChange() 方法中的循环:

    public void onDataChange(DataSnapshot dataSnapshot) {
        if (ds.exists()) {
            UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
            String name = userInformation.getName();
            mWelcomeUserMessage.setText(name);
            //logging name
            Log.d("My activity", "name of user with userID - " + id + " is : " + userInformation.getName());
        }
    }
    

    只有在使用带有值侦听器的查询时才需要循环,因为一个查询可以有多个结果。但是在您的情况下,您可以直接访问正确的子节点,因此不需要循环。

    【讨论】:

      【解决方案2】:

      您正在尝试访问不存在的孩子,这就是您获得空值的原因。您的听众已经在收听“id child”,请替换以下行:

       UserInformation userInformation = ds.child(id).getValue(UserInformation.class);
      

      作者:

       UserInformation userInformation = ds.getValue(UserInformation.class);
      

      然后,回到您的 UserInformation.class,添加以下更改:

      @IgnoreExtraProperties // Add this tag
      public class UserInformation {
      
          private String name;
          private String student_number;
          private String faculty;
          private boolean isAdmin;
      
          //Define this constructor
          public UserInformation() {
              // Default constructor required for calls to DataSnapshot.getValue(UserInformation.class)
          }
          // The rest of your class ...
      
      }
      

      【讨论】:

      • 我进行了更改,但现在,当我尝试在我的 textView 上调用 setText() 时,我没有得到任何东西,而不是空指针异常。此外,这显示在我的日志中:06-05 16:10:09.022 4812-4812/com.example.android.fireapp D/我的活动:具有用户 ID 的用户名称 - ITDpaqPfEFY7AdE20vjHbeU84eV2 为:null。 由于某种原因,该字段仍然为空
      • 你能发布你的 UserInformation.java 吗? @YashChowdhary
      • 所以我在默认构造函数中给了它一个默认值“”,这就是显示的内容。似乎 getValue() 方法不会改变 'name' 属性
      • 您是否按照我告诉您的那样修改了 UserInformation 类?默认构造函数必须为空 @YashChowdhary
      • 是的,我添加了默认构造函数并给了所有属性默认值(对所有字符串,我分配了“”,我将“false”分配给布尔值)@AlexTa
      猜你喜欢
      • 2016-11-16
      • 2021-12-28
      • 1970-01-01
      • 2019-09-29
      • 2022-11-11
      • 2017-01-13
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多