从特定节点的Firebase数据库中检索数据

时间:2018-09-02 16:59:19

标签: android firebase firebase-realtime-database

我正在开发一个android应用程序,现在我只能从特定的节点中检索数据,就像我只想从每个节点中检索一个值一样。数据库结构如下所示。

Database Structure

如何检索由Firebase数据库创建的第二个唯一ID?

2 个答案:

答案 0 :(得分:1)

首先创建一个POJO类以获取所需的值,它的写法应与在Firebase中获取它们的方式相同。

public class AppointmentsPojo {

    private String appointmentStuts;

    public AppointmentsPojo(){

    }


    public String getAppointmentStuts() {
        return appointmentStuts;
    }

    public void setAppointmentStuts(String appointmentStuts) {
        this.appointmentStuts = appointmentStuts;
    }

}

然后在Appointments内循环获取每个appointmentStuts

mDatabase.child("Appointments").addListenerForSingleValueEvent(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    //Looping inside Appointments to get each appointmentsStuts
    for(DataSnapshot snapshot: dataSnapshot.getChildren()){
    AppointmentsPojo ap = snapshot.getValue(AppointmentsPojo.class);
    //Getting each appointmentStuts
     String appointmentStuts = ap.getAppointmentStuts();
     //To get each father of those appointments 
     String key = snapshot.getKey();

      Log.e("Data: " , "" + appointmentStuts );

       }

  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    System.out.println("The read failed: " + databaseError.getCode());
  }
});

mDatabase在哪里

DatabaseReference mDatabase;

mDatabase = FirebaseDatabase.getInstance().getReference();

答案 1 :(得分:0)

要仅从第一个对象获取appointmentStuts的值,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Appointments").child(PostKey).limitToFirst(1);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String appointmentStuts = ds.child("appointmentStuts").getValue(String.class);
            Log.d(TAG, appointmentStuts);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
query.addListenerForSingleValueEvent(valueEventListener);