我有一个Java类(CourseViewTeachers),我正在其中使用用户的uid从firebase数据库中读取用户名。我编写了代码来读取此类构造函数中的数据。 构造函数如下。
public CourseViewTeachers(Courses courses)
{
super(courses.getCourse_uid(), courses.getTecher_uid(), courses.getName());
databaseReference = FirebaseDatabase.getInstance().getReference().child("users").child(getTecher_uid());
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User teacher = dataSnapshot.getValue(User.class);
teacherName = teacher.getUser_name();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
我正在使用此类填充自定义数组适配器。当我在一个片段中创建此类的对象并返回变量'teacherName'时,它返回null。
我在其中填充适配器的代码在下面给出
courseListView = view.findViewById(R.id.my_courses_list);
courseListView.setAdapter(adapter);
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
courseList.clear();
for(DataSnapshot snapshot : dataSnapshot.getChildren())
{
CourseViewTeachers courses = new CourseViewTeachers(snapshot.getValue(Courses.class));
if(courses.getTecher_uid().equals(fb_user.getUid()))
{
courseList.add(courses);
}
}
adapter.notifyDataSetChanged();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
我有两个问题:
编辑:以阐明我在哪里得到空值
第二个代码片段中的adapter变量是自定义数组适配器类的对象。在arrayAdapter的getView()函数中调用CourseViewTeachers类的getTeacherName()函数,该函数仅返回变量'teacherName'的值。
自定义数组适配器的代码:
public class CourseViewTeachersAdapter extends ArrayAdapter<CourseViewTeachers> {
private Context context;
private List<CourseViewTeachers> list;
public CourseViewTeachersAdapter(@NonNull Context context, ArrayList<CourseViewTeachers> list)
{
super(context, 0 , list);
this.context = context;
this.list = list;
}
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent)
{
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(context).inflate(R.layout.course_view_teachers_layout,parent,false);
CourseViewTeachers obj = list.get(position);
TextView courseView = listItem.findViewById(R.id.course_teachers_view_course_name);
courseView.setText(obj.getName());
TextView teacherName = listItem.findViewById(R.id.course_teachers_view_teacher_name);
teacherName.setText("Teacher : " + obj.getTeacherName());
return listItem;
}
}