我想显示所有日期的dayVisitors。因此,我想访问Noida Sec1 /下所有日期的daydayVisitors。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.
答案 0 :(得分:2)
如果您只想专门访问Noida Sec 1下的dayVisitors,则可以使用以下方法简单实现:
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 :(得分:0)
首先获得对Noida Sec 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);