Reputation: 11
I am developing an Attendance App. I want to retrieve students list with number of presents and populate it in a list view.
I have tried the below code but i am getting number of presents of one specific student.
DatabaseReference ref =
FirebaseDatabase.getInstance().getReference().child("Students
Attendance").child(selectedItem).child(id).child(subject);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
Userlist.add(dataSnapshot.getValue().toString());
addStudents(Userlist);
}else {
Toast.makeText(getApplicationContext(), "****NO Record
FOUND****", Toast.LENGTH_LONG).show();
}
}
I expect the output as a list of students with their number of presents populated in list view.
Upvotes: 0
Views: 220
Reputation: 658
Since you are making an app that counts a number of presents of a particular student. You can do it this way:
First you can set the value to be stored in the database as :
mFirebaseDatabaseReference.push().setValue(new String[]{student_name,attendance})
This stores the data as :- Sam,70 and Mike,75
Now retrive that data using ChildEventListener:
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
String data = dataSnapshot.getValue();
mMyAdapter.add(data);
);
One thing to not here is that, you dont necessarily need to put the student_id as we using the push()
method here so it gives every child a new id so that we don't have to worry about the data being disturbed for students with the same name or marks.
Upvotes: 1
Reputation: 11
ref.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
String value = dataSnapshot.getValue().toString();
String key = dataSnapshot.getKey();
String record = key + ": " + value;
Userlist.add(record);
addStudents(Userlist);
}
It worked for me.
Upvotes: 0