firebase database keys to arraylist

旧时模样 提交于 2019-12-25 18:58:14

问题


i am trying to add the keys from a firebase database to an arraylist in my onDataChange method.

        mDatabase = FirebaseDatabase.getInstance().getReference("events");
    mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if(dataSnapshot.exists()) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

                            String event = snapshot.getKey();
                            Log.d("did it work??", event);
                            eventList.add(event);
                        }
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {
                }
            });

when i log event it'll print but its not adding to eventList arrayList


回答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:

@Override
public void onDataChange(DataSnapshot snapshot) {
    ArrayList<String> ids = new ArrayList<String>();
    for (DataSnapshot childSnapshot: snapshot.getChildren()) {
        ids.add(childSnapshot.getValue().toString());
    }
}



回答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 = new ArrayList<>();

If you want to use that ArrayList outside the onDataChange() method, than see my answer from this post.

Hope it helps.



来源:https://stackoverflow.com/questions/44726269/firebase-database-keys-to-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!