Accessing Firebase Database Objects Below Child

 ̄綄美尐妖づ 提交于 2021-01-29 05:44:06

问题


I have a data structure as such:

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?


回答1:


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

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.



来源:https://stackoverflow.com/questions/52691457/accessing-firebase-database-objects-below-child

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