我想显示所有日期的dayVisitors。因此,我想访问所有下诺伊达秒-1的dayVisitors /所有dates.Database structure This is what I've done but it gives null pointer error: Attempt to invoke virtual method 'java.lang.String com.example.thehighbrow.visitormanagement.DayVisitor.getName()' on a null object reference.
如果你想具体访问下诺伊达秒只是dayVisitors 1,你可以简单地实现这一点使用:
final FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference ref = db.getReference("Noida Sec1");
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
if(childSnapshot.hasChild("dayVisitor")) {
for (DataSnapshot visitorSnapshot : childSnapshot.child("dayVisitor").getChildren()) {
Visitor visitorObject = visitorSnapshot.getValue(Visitor.class); //or whatever your dayVisitor object is
//now you can access visitorObject with the fields you created and do whatever like add it to an arraylist
}
}
}
} @Override
public void onCancelled(DatabaseError databaseError) {
Log.e("READ FAILED", databaseError.getMessage());
}
});
我不知道你的代码是干什么的,不过,我建议,如果可能的话,你尝试格式化您的数据库布局要尽可能平坦,因为以这种方式嵌套数据可能会变得非常混乱和效率低下。也许让dayVisitor场访港,而不是它自己的子节点。
首先,获得参考诺伊达秒1一样的孩子:
DatabaseReference mNoidaReference = mFirebaseDatabase.getReference().child("Noida Sec1");
现在做一个childEventListener它并通过它循环找到dayVisitor孩子
ChildEventListener mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
for(Datasnapshot data: dataSnapshot.child("dayVisitor")){
String dayVisitor = data.getValue();
}
}
@Override
public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
mNoidaReference.addChildEventListener(mChildEventListener);