Firebase Data to ListView | Android App Development | Lecture#46 | Hive Learners
饾摉饾摶饾摦饾摦饾摻饾摬饾摲饾摪饾摷
Hello, dear Hive Learners, I hope you all are well. In the 45th lecture, we learn how to retrieve the data from the Firebase real-time database. But we show the data in an unprocessed way. It was just a JSON string that we retrieve in the lecture. Today we will learn how to process data and we will also populate the listview with the firebase data, Let's jump into it.
GitHub Link
Use this GitHub project to clone into your directory. The following lecture will update it so you will never miss the latest code. Happy Coding!
What Should I Learn
- Populate the ListView with Firebase Data
Assignment
- Retrieve and Show Firebase Data in a List
Procedure
First, we need to add a loop where we will get all the elements. It is a For-each loop. We will use the sign : to map the data of the next variable. In this loop, we will use the children's map.
Now we can process the data value by value or we can create a model class that can auto-map the values. Let's get it one by one.
Now we can use these values to set in the model class that we already have MyList_POJO. We need to manually add data in this POJO class as the name of variables in the class is not same as the variables in the firebase. I removed the static value that we have set before.
We also need to clear the list on value change before the for loop so there will be no duplication on value change.
myList_pojos.clear();
for (DataSnapshot ds : snapshot.getChildren()) {
String username = ds.child("account").getValue(String.class);
Float amount = ds.child("amount").getValue(Float.class);
myList_pojos.add(new MyList_POJO(username, String.valueOf(amount)));
}
After the for loop, we need to notify the Adapter that the value is now changed in the POJO class and show the new value. This will refresh our list with the new changes.
Now, let's run the app and check if we get the data in the listview or not.
We are getting the amount but not the username. Let's check the adapter. I check it and we had set the wrong reference id for the title.
So we need to fix it and set the correct id for the title textview.
let's run the app again.