I have wandered YouTube and Stack Overflow in search of way to retrieve the teacherName value from the following database:
I have not yet found a solution for my problem, whether I use a Value or ChildEventListener. This is the code I'm using:
public class ViewTeachersActivity extends AppCompatActivity {
// Define the Teacher Firebase DatabaseReference
private DatabaseReference databaseTeachers;
// Define a String ArrayList for the teachers
private ArrayList<String> teachersList = new ArrayList<>();
// Define a ListView to display the data
private ListView listViewTeachers;
// Define an ArrayAdapter for the list
private ArrayAdapter<String> arrayAdapter;
/**
* onCreate method
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_teachers);
// Associate the Teacher Firebase Database Reference with the database's teacher object
databaseTeachers = FirebaseDatabase.getInstance().getReference();
databaseTeachers = databaseTeachers.child("teachers");
// Associate the teachers' list with the corresponding ListView
listViewTeachers = (ListView) findViewById(R.id.list_teachers);
// Set the ArrayAdapter to the ListView
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teachersList);
listViewTeachers.setAdapter(arrayAdapter);
// Attach a ChildEventListener to the teacher database, so we can retrieve the teacher entries
databaseTeachers.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// Get the value from the DataSnapshot and add it to the teachers' list
String teacher = dataSnapshot.getValue(String.class);
teachersList.add(teacher);
// Notify the ArrayAdapter that there was a change
arrayAdapter.notifyDataSetChanged();
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I have also tried using a for loop inside the ChildEventListener, but that also didn't work. Can anyone point me to a solution?