当前位置: 首页 > 知识库问答 >
问题:

Firebase 数据库异常:尝试调用虚拟方法 'java.lang...'在空对象引用上

吕作人
2023-03-14

我已经到处搜索并尝试了他们关于如何调用虚拟方法的方法,但结果仍然是一样的。请帮助我,我不知道我的错误在哪里。

当我在手机上运行我的应用程序时,它会引发以下异常

尝试对空对象引用调用虚拟方法“Java . lang . string my package . studentin information . get userid()”

@Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

  //FirebaseAuth
        firebaseAuth = FirebaseAuth.getInstance();
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            userID = user.getUid();
        }
        //Realtime Firebase
        firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference newData = firebaseDatabase.getReference();
        //Display data
        newData.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                try {
                    showData(dataSnapshot);
                } catch (Exception e) {
                    Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
}

方法showData()

 private void showData(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            studentInformation studentData = new studentInformation();
            studentData.setUserID(ds.child(userID).getValue(studentInformation.class).getUserID());
            studentData.setStudentFullName(ds.child(userID).getValue(studentInformation.class).getStudentFullName());
            studentData.setStudentID(ds.child(userID).getValue(studentInformation.class).getStudentID());
            studentData.setEmail(ds.child(userID).getValue(studentInformation.class).getEmail());
            studentData.setCampus(ds.child(userID).getValue(studentInformation.class).getCampus());
            studentData.setCourse(ds.child(userID).getValue(studentInformation.class).getCourse());
            studentData.setIntake(ds.child(userID).getValue(studentInformation.class).getIntake());
        }
    }

班级学生信息()

package mypackage;

import com.google.firebase.database.IgnoreExtraProperties;

@IgnoreExtraProperties
public class studentInformation {

    private String userID;
    private String studentFullName;
    private long studentID;
    private String email;
    private String campus;
    private String course;
    private String intake;

    studentInformation() {
    }

    studentInformation(String userID, String studentFullName, long studentID, String email, String campus, String course, String intake) {
        this.userID = userID;
        this.studentFullName = studentFullName;
        this.studentID = studentID;
        this.email = email;
        this.campus = campus;
        this.intake = intake;
    }

    public String getStudentFullName() {
        return studentFullName;
    }

    public void setStudentFullName(String studentFullName) {
        this.studentFullName = studentFullName;
    }

    public long getStudentID() {
        return studentID;
    }

    public void setStudentID(long studentID) {
        this.studentID = studentID;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getCampus() {
        return campus;
    }

    public void setCampus(String campus) {
        this.campus = campus;
    }

    public String getCourse() {
        return course;
    }

    public void setCourse(String course) {
        this.course = course;
    }

    public String getIntake() {
        return intake;
    }

    public void setIntake(String intake) {
        this.intake = intake;
    }

    public String getUserID() {
        return userID;
    }

    public void setUserID(String userID) {
        this.userID = userID;
    }
}

Firebase数据库:我导出它并从json更改为txt。

{
  "main" : {
    "home" : {
      "announcement-date" : "jkljlkjdaj",
      "campus" : {
        "unikl-miit" : {
          "course" : {
            "bcem" : {
              "courseName" : "BCEM"
            }
          }
        },
        "unikl-mimet" : {
          "course" : {
            "bse" : {
              "courseName" : "BSE"
            }
          }
        }
      }
    }
  },
  "student" : {
    "6LKSe5oqfwgrkEV57NXQekDvNhl1" : {
      "campus" : "UniKL MIIT",
      "course" : "Diploma In Animation",
      "email" : "hazman@gmail.com",
      "intake" : "55",
      "studentFullName" : "haMan",
      "studentID" : 52213116153,
      "userID" : "6LKSe5oqfwgrkEV57NXQekDvNhl1"
    },
    "evPFfkE1VtObUlBNz8pizSNKt662" : {
      "campus" : "UniKL MIIT",
      "course" : "Bachelor of Multimedia Technology (Hons) in Interactive Multimedia Design (BIMD)",
      "email" : "fakyou@gmshit.com",
      "intake" : "69",
      "studentFullName" : "Adam",
      "studentID" : 52213116190,
      "userID" : "evPFfkE1VtObUlBNz8pizSNKt662"
    },
    "rcUgnUBqd4Xb3AxmngE3OD1BBpd2" : {
      "campus" : "UniKL MIIT",
      "email" : "hazman45@gmail.com",
      "intake" : "52/49/4",
      "studentFullName" : "jwjajs",
      "studentID" : 52213116153,
      "userID" : "rcUgnUBqd4Xb3AxmngE3OD1BBpd2"
    },
    "z46FjWQE8TRYiJxIexMkrp6gSYv2" : {
      "campus" : "UniKL MIIT",
      "email" : "zoowake97@gmail.com",
      "intake" : "16/9/18",
      "studentFullName" : "Eisom",
      "studentID" : 52213116132,
      "userID" : "z46FjWQE8TRYiJxIexMkrp6gSYv2"
    }
  }
}

问题[更新]:

//FirebaseAuth
        firebaseAuth = FirebaseAuth.getInstance();
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            userID = user.getUid();

            DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("student");
            DatabaseReference currentUserRef = usersRef.child(userID);
            currentUserRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    studentData = dataSnapshot.getValue(studentInformation.class);

                    //studentID I delcared outside the onCreate. Does the 'studentID' store from Firebase?
                    studentFullName = studentData.getStudentFullName();//This one

                    textViewEmail.setText(studentData.getEmail());//Its working, display
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    throw databaseError.toException(); // don't ignore errors
                }
            });
        }
        //At 'onCreate'
        textViewStudentName.setText(studentFullName); //Can I do like this?

更新于2018年6月16日问题:

我想在新的firebaseDatabaseCampus中实现Firebase数据库的价值。

我做了这个,应用程序崩溃了。请帮帮我。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //Inflate the layout for this fragment
    View viewMain = inflater.inflate(R.layout.fragment_campus, container, false);

    recyclerView = viewMain.findViewById(R.id.recycleViewCampus);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));//Ini penting nak display

    firebaseAuth = FirebaseAuth.getInstance();//Ini penting
    firebaseDatabase = FirebaseDatabase.getInstance();

    //So retrieve data
    userID = firebaseAuth.getUid();
    databaseReferenceStudent = firebaseDatabase.getReference().child("student").child(userID);
    databaseReferenceStudent.addValueEventListener(new ValueEventListener() { //So sini kita ambik value campus ~ UniKL MIIT
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            studentData = new studentInformation();//Ini declare
            studentData = dataSnapshot.getValue(studentInformation.class);

            //1. So student.getCampus is here
            databaseReferenceCampus = firebaseDatabase.getReference().child("campus").child(studentData.getCampus()).child("post");
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
    return viewMain;
}

//On Start
@Override
public void onStart() {
    super.onStart();
    FirebaseRecyclerAdapter<campus, CampusViewHolder> firebaseRecyclerAdapterCampus =
            new FirebaseRecyclerAdapter<campus, CampusViewHolder>(
                    campus.class,
                    R.layout.campus_row,
                    CampusViewHolder.class,
                    databaseReferenceCampus     //So the value getCampus is here?
            ) {
                @Override
                protected void populateViewHolder(CampusViewHolder viewHolder, campus model, int position) {
                    viewHolder.setDetails(getContext(), model.getImage(), model.getTitle(), model.getDate(), model.getShortDescription());
                }
            };
    //setAdapter
    recyclerView.setAdapter(firebaseRecyclerAdapterCampus);
}

共有1个答案

萧永望
2023-03-14

您正在从根读取所有数据,然后遍历子级。相反,您会希望在学生节点中读取更低一级的数据:

DatabaseReference rootRef = firebaseDatabase.getReference();
rootRef.child("student").addValueEventListener(new ValueEventListener() {
    ...

更新:我现在感觉你只是想读取当前用户的数据。在这种情况下,代码是:

if (user != null) {
    userID = user.getUid();
    DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("user");
    DatabaseReference currentUserRef = usersRef.child(userID);
    currentUserRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            studentInformation studentData = dataSnapshot.getValue(studentInformation.class)
            ...    
        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });
}
 类似资料:
  • 我正试图从这个链接将数据从Android应用程序发送到Raspberry pi。我已经执行了其中提到的所有步骤,但当我尝试运行该应用程序时,在android studio logcat中会出现一个错误。 错误类似于:java.lang.NullPointerExcture:尝试在空对象引用上调用虚拟方法'intorg.json.JSONObject.getInt(java.lang.String)

  • 我正在尝试实现一个外部色轮,它应该出现在的片段一直在崩溃我的应用程序。我想我明白为什么会发生这种情况,但是在尝试修复它大约6个小时后,我就要放弃了。我知道之前有人问过这个问题,但是我无法为我的特定问题导出一个修复程序。下面是我的代码: 这是Logcat错误: 如果有人能帮我解决这个问题,那就太好了。提前谢谢^^ 编辑:这是我的XML,按要求:

  • 我的应用程序有问题,我想解决它,但我无法访问解决方案,请帮助我,,,

  • 问题内容: 我收到以下错误 尝试在空对象引用上调用虚拟方法’void android.widget.StackView.setAdapter(android.widget.Adapter)’ 在这条线上 完整的片段 EventsFragment.java 是 Stack_Adapter.java Stack_Items 问题答案: 您正在执行: 你是。返回。 你为什么用? 在哪里?您应该从正确的x

  • 我的应用程序有问题,想解决它,但我无法访问解决方案,请帮帮我,,

  • 问题内容: 我尝试使用片段来打开数据库,但是,当我单击按钮开始搜索时,程序意外终止,并显示如下错误: 主片段: DBManager类: 顺便说一句,我在MainAcitivity中使用了有关DBManager的代码,并且成功了。将代码复制到上面的片段后,它失败了,该怎么办? 问题答案: 之前和之后你都做不到。 因为,您正在执行片段实例化时。该方法将始终返回null。另外,尽量不要将参考文献保留在您