kleineroid
kleineroid

Reputation: 33

How to retrieve and display data from Firebase onto a ListView?

I have wandered YouTube and Stack Overflow in search of way to retrieve the teacherName value from the following database:

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?

Upvotes: 3

Views: 11995

Answers (2)

Preston Garno
Preston Garno

Reputation: 1215

Since your question is unclear if you want to listen for all teacherNames or just one.

This is an easy way to get all 'teacherName' for every entry (uuid key) under /teachers and adds a listener to this query:

FirebaseDatabase.getInstance()
    .getReference()
    .child("teachers")
    .orderByChild("teacherName")
    .addValueEventListener(listener); //listener example below


ValueEventListener listener = new new ValueEventListener()
    {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot)
        {
            dataSnapshot.getChildren().forEach(

               // assuming you are using RetroLambda, if not, implement Consumer<? super T> action
                // update change ListView here
            );
        }


        @Override
        public void onCancelled(FirebaseError firebaseError)
        {
            //handle errors here
        }
    });

If you are looking for getting a specific teacher name, comment and I'll change it. Also, I haven't tested syntax as I'm on mobile, so treat this as pseudocode but it should get you going in the right direction

Check out the Firebase Query documentation, it is really straightforward and as of now can do really powerful stuff in a few lines of code. Be careful of outdated tutorials when searching, Firebase has added allot of its functionality in the last ~1 year

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191701

String teacher = dataSnapshot.getValue(String.class);

You don't have a String there. You have an object.

So, you need a Java class

public class Teacher {
    String teacherID, teacherEmail; // etc. all fieldnames in the database

    public Teacher() {
    }

    // getters

    // setters

    @Override
    public String toString() {
        return this.teacherID + ": " + this.teacherEmail;
    }
}

Then from Firebase, you can map the snapshot to that class and add to an adapter.

Teacher teacher = (Teacher) dataSnapshot.getValue(Teacher.class);
String teacherString = String.valueOf(teacher);
arrayAdapter.add(teacherString);

Refer: Firebase-UI | Using Firebase to populate ListView

Upvotes: 3

Related Questions