Reputation: 15
I want to display dayVisitors of all the dates. Hence i want to access all the dayVisitors under Noida Sec1/ all 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.
Upvotes: 0
Views: 208
Reputation: 161
If you want to specifically access just the dayVisitors under Noida Sec 1 you can simply implement this using:
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());
}
});
I'm not sure what your code is doing, however, I do suggest, if possible, you try to format your database layout to be as flat as possible because nesting data in this manner can get very messy and inefficient. Maybe make dayVisitor a field in visitor rather than its own child node.
Upvotes: 1
Reputation: 658
First of all get the reference to the children of Noida Sec 1 like:
DatabaseReference mNoidaReference = mFirebaseDatabase.getReference().child("Noida Sec1");
Now make a childEventListener for it and loop through it to find the dayVisitor child
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);
Upvotes: 0