yeo yeo - 1 month ago 11
Android Question

Retrieving child's Information from Firebase back to android studio

I am new to android studio and firebase itself. I understand that in order to get the child's data from its unique ID, I might need to use a datasnapshot method. For example, I need to retrieve the "name" from firebase database back to android studio application. How do I implement it in this case? Help would be much appreciated!

enter image description here

Below is my current code

root.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Set<String> set = new HashSet<String>();
Iterator i = dataSnapshot.getChildren().iterator();

while (i.hasNext()){
set.add(((DataSnapshot)i.next()).getKey());

}
names.clear();
names.addAll(set);

arrayAdapter.notifyDataSetChanged();

Answer

I'll assume that root refers to the root of your database. In that case your onDataChange will get a snapshot of the entire data at that location. You can loop over them and get the properties of each child in turn with:

root.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Set<String> set = new HashSet<String>();
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            //set.add(childSnapshot.getKey());
            set.add(childSnapshot.child("name").getValue(String.class));
        }
        names.clear();
        names.addAll(set);

        arrayAdapter.notifyDataSetChanged();

But I highly recommend that you create a Java class that represents the items in your list. In your case that can be as simple as:

public class Item {
    public string name;
    public string pos;
    public string team;
}

Then you can read the items with:

root.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Set<String> set = new HashSet<String>();
        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
            Item child = childSnapshot.getValue(Item.class);
            set.add(item.name);
        }
        names.clear();
        names.addAll(set);

        arrayAdapter.notifyDataSetChanged();