My Child List Screenshot
I need to get the number of childs (No nested childs are there!) and store it in a global public variable. Also, I want all the childs to put in a string array list.
Thanks in advance!
My Child List Screenshot
I need to get the number of childs (No nested childs are there!) and store it in a global public variable. Also, I want all the childs to put in a string array list.
Thanks in advance!
Use some form of listener. For single lookup use the valueEventListener.
Then in the OnDataChange() method that is automatically generated. Use the datasnapshot to get the childrenCount and then to loo through the children and add them to the list
List<String> list = new ArrayList<>();
long childrenCount;
public void getListItems()
{
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
childrenCount = dataSnapshot.child("searchingUsers").getChildrenCount();
for (DataSnapshot snap : dataSnapshot.child("searchingUsers").getChildren())
{
//If you want the node value
list.add(snap.getValue().toString());
//If you want the key value
list.add(snap.getKey());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
}
This makes both the variables global in the Activity. So you can reach them from anywhere in the Activity
To get a list of all those random values, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference searchingUsersRef = rootRef.child("searchingUsers");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String value = ds.getValue(String.class);
list.add(value);
}
//Do what you need to do with your list
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
searchingUsersRef.addListenerForSingleValueEvent(valueEventListener);
As you can see I have used the list only inside the callback, if you want to use the list outside, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.