firebase数据库键到arraylist [英] firebase database keys to arraylist

查看:113
本文介绍了firebase数据库键到arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试将firebase数据库中的键添加到我的onDataChange方法中的ArrayList中。

  mDatabase = FirebaseDatabase.getInstance()。getReference(events); 
mDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
@Override $ b $ public void onDataChange(DataSnapshot dataSnapshot){$ b $ if(dataSnapshot.exists()){
for DataSnapshot快照:dataSnapshot.getChildren()){

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

当我登录事件时,它会打印,但不会添加到事件列表arrayList

$ b如果您希望将整个快照传递给侦听器,请使用 addValueEventListener code> addListenerForSingleValueEvent 。



如果使用 addValueEventListener 如果数据库发生变化,则调用初始快照。



如果使用 addListenerForSingleValueEvent ,侦听器将会被初始快照调用一次。



侦听器收到的快照将包含所有的子项。要迭代他们,你可以这样做:

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


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

解决方案

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());
    }
}

这篇关于firebase数据库键到arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆