【问题标题】:Firebase get error when data is null from database当数据库中的数据为空时,Firebase 会出错
【发布时间】:2026-02-11 21:30:02
【问题描述】:
FirebaseRef.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot snapshot) {
        name = snapshot.child("username").getValue().toString();
        String myUrl = snapshot.child("photoURL").getValue().toString();
        txtFullName.setText(name);
        txtWelcome.setText("Hoşgeldin " + name);

        if(myUrl.isEmpty()) {
            changePhotoWithName(name);
        }
        else {
            changePhoto(myUrl);
        }
    }
}

这是我的代码,使用 FirebaseRef 侦听数据库并检索数据,但问题是我的数据同时为空并出现错误。

【问题讨论】:

标签: android firebase firebase-realtime-database


【解决方案1】:
FirebaseRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot snapshot) {

            if(snapshot.exists()){
                name = snapshot.child("username").getValue().toString();
                String myUrl = snapshot.child("photoURL").getValue().toString();
                txtFullName.setText(name);
                txtWelcome.setText("Hoşgeldin " + name);

                if(myUrl.isEmpty()){
                    changePhotoWithName(name);
                }
                else {
                    changePhoto(myUrl);
                }

            }

        }

【讨论】:

  • 很高兴听到这个消息:)
【解决方案2】:

试试这个..

    if(myUrl.length()>0){
      if(myUrl.isEmpty()){
          changePhotoWithName(name);
       }
        else {
            changePhoto(myUrl);
        }
   }

【讨论】: