如何在Android上的Firebase Databse上检索特定列表项

时间:2018-08-15 08:42:50

标签: android firebase-realtime-database

teamapp-25ba7
  schedules
    -LHc3zKZhNFLq536dpA1
      UID:    
      date:
      details:
      time:
      title:
    -LHc7MBAoNwLWCNgkZ_y
      UID:
      date:
      details:
      time:
      title: 

从上面的节点示例中,我只想获取详细信息和时间值,我的问题是如何只检索这两个值。我尝试遍历所有值,但这让我得到了一切

1 个答案:

答案 0 :(得分:1)

假设您要从所有对象中获取detailstime属性的值,并假设details属性的类型为String,而time ServerValue.TIMESTAMP ,要解决此问题,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference schedulesRef = rootRef.child("schedules");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String details = ds.child("details").getValue(String.class);
            long time = ds.child("time").getValue(Long.class);
            Log.d("TAG", details + " / " + time);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {}
};
schedulesRef.addListenerForSingleValueEvent(valueEventListener);