在子级下方访问Firebase数据库对象 [英] Accessing Firebase Database Objects Below Child

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

问题描述

我有这样的数据结构:

我在民意测验引用上调用 .addListenerForSingleValueEvent(),并且我有一个Pojo类映射到民意测验.但是,由于我不知道键的值,因此无法访问我的投票项.有没有办法访问显示名称,或者我是否需要知道键的值?

I am calling .addListenerForSingleValueEvent() on my Polls reference, and I have a Pojo class mapped to the poll. However, since I do not know the value of the key, I cannot access my poll items. Is there a way to access, let's say, display_name, or would I need to know the value of the key?

推荐答案

如果您不知道要显示的民意测验,最好的办法就是显示所有民意测验.这可以通过将侦听器附加到/Polls :

If you don't know anything about the poll to show, the best you can do is show all polls. This can be done by attaching a listener to /Polls:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Polls");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot pollSnapshot: dataSnapshot.getChildren()) {
            Poll poll = pollSnapshot.getValue(Poll.class);
            String key = pollSnapshot.getKey();
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

如果要访问特定的民意测验,则必须知道一些可以唯一标识该民意测验的知识.最简单的方法就是知道它的密钥,在这种情况下,您可以像这样加载它:

If you want to access a specific poll, you must know something that unique identifies that poll. The simplest of this is knowing its key, in which case you can load it like this:

String key = "-LNlisBxkPbxd00a_QH";
ref.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Poll poll = pollSnapshot.getValue(Poll.class);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

如果您不知道键,则需要知道要选择的民意调查属性的值.例如,要获取问题 y89yuvyu 的所有民意调查,您可以使用以下方式查询该孩子:

If you don't know the key, you need to know a value of a property of the poll to select. For example to get all polls for question y89yuvyu you can query for that child with:

ref.orderByChild("question").equalToChild("y89yuvyu").addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot pollSnapshot: dataSnapshot.getChildren()) {
            Poll poll = pollSnapshot.getValue(Poll.class);
            String key = pollSnapshot.getKey();
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

由于可能对该问题值进行多次民意调查,因此您需要像上面一样再次遍历结果.

Since there may be multiple polls for that question value, you'll need to loop over the results again as I've done above.

这篇关于在子级下方访问Firebase数据库对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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