Firebase Database Keys To Arraylist
Solution 1:
If you want the entire snapshot to be delivered to the listener, use either addValueEventListener
or addListenerForSingleValueEvent
.
If you use addValueEventListener
, the listener will be called with the initial snapshot and again if the database changes.
And if you use addListenerForSingleValueEvent
, the listener will be called only once with the initial snapshot.
The snapshot received by the listener will include all of the children. To iterate them you would do something like this:
@OverridepublicvoidonDataChange(DataSnapshot snapshot) {
ArrayList<String> ids = newArrayList<String>();
for (DataSnapshotchildSnapshot: snapshot.getChildren()) {
ids.add(childSnapshot.getValue().toString());
}
}
Solution 2:
This is happening because onDataChange
method is called asynchronously. This means that the statement that adds the strings to the ArrayList
is executed before onDataChange()
method has been called. That's why your list is empty outside that method. So in order to use that ArrayList
, you need to declare and use it inside the onDataChange()
method.
ArrayList<String> ids = newArrayList<>();
If you want to use that ArrayList
outside the onDataChange()
method, than see my answer from this post.
Hope it helps.
Post a Comment for "Firebase Database Keys To Arraylist"