Android Studio中如何从Firebase实时数据库获取已接受预约的特定咨询师
解决方案
你的问题核心在于当前代码直接拉取了所有咨询师数据,没有关联Appointment节点里的预约状态信息。要只显示接受当前用户预约的咨询师,我们需要先找到当前用户对应的「已接受预约」记录,再根据记录里的咨询师ID加载对应的信息。
步骤说明
- 获取当前登录用户(患者)的UID;
- 查询
Appointment节点,筛选出当前用户发起且状态为Accepted的预约,提取对应的咨询师ID; - 根据咨询师ID,从
Counsellors节点加载该咨询师的信息并展示。
修改后的代码
private void displayData(){ FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser(); if(firebaseUser == null) return; // 处理用户未登录的边界情况 String currentPatientId = firebaseUser.getUid(); // 第一步:查询当前用户已被接受的预约 DatabaseReference appointmentRef = FirebaseDatabase.getInstance().getReference("Appointment"); appointmentRef.orderByChild("idPatient").equalTo(currentPatientId) .addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { mUsers.clear(); // 清空列表,避免重复数据 for(DataSnapshot appointmentSnapshot : dataSnapshot.getChildren()){ Appointment appointment = appointmentSnapshot.getValue(Appointment.class); // 只处理状态为"Accepted"的预约 if(appointment != null && "Accepted".equals(appointment.getStatus())){ String acceptedCounsellorId = appointment.getIdDoctor(); // 第二步:根据咨询师ID获取对应的信息 DatabaseReference counsellorRef = FirebaseDatabase.getInstance().getReference("Counsellors").child(acceptedCounsellorId); counsellorRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot counsellorSnapshot) { Counsellors counsellor = counsellorSnapshot.getValue(Counsellors.class); if(counsellor != null){ mUsers.add(counsellor); userAdapter.notifyDataSetChanged(); // 实时更新列表 } } @Override public void onCancelled(@NonNull DatabaseError error) { // 处理咨询师信息查询错误 } }); } } // 初始化或更新适配器 if(userAdapter == null){ userAdapter = new UserAdapter(getContext(), mUsers); recyclerView.setAdapter(userAdapter); } else { userAdapter.notifyDataSetChanged(); } } @Override public void onCancelled(@NonNull DatabaseError error) { // 处理预约查询错误 } }); }
补充说明
- Appointment实体类:你需要创建一个对应数据库字段的实体类,Firebase才能正确解析数据:
public class Appointment { private String date; private String idDoctor; private String idPatient; private String status; private String time; // Firebase要求的空构造函数 public Appointment() {} // Getter和Setter方法 public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getIdDoctor() { return idDoctor; } public void setIdDoctor(String idDoctor) { this.idDoctor = idDoctor; } public String getIdPatient() { return idPatient; } public void setIdPatient(String idPatient) { this.idPatient = idPatient; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } }
- 多预约适配:如果后续用户有多个已接受的预约,这段代码会自动加载所有符合条件的咨询师,无需额外修改。
- 监听模式选择:如果需要实时监听预约状态变化(比如咨询师后续修改了预约状态),保持
addValueEventListener即可;如果只需要一次性加载数据,可以换成addListenerForSingleValueEvent来减少资源消耗。
内容的提问来源于stack exchange,提问作者Gavin Teo Juen
相关产品推荐
相关产品推荐

