如何从firebase中的值中获取密钥 [英] How to get the key from the value in firebase
问题描述
当我知道 Firebase 的以下结构中的字段name"包含efg"时,如何获取密钥-KLpcURDV68BcbAvlPFy".
How do I get the key "-KLpcURDV68BcbAvlPFy" when I know the field "name" contains "efg" in the following structure in Firebase.
clubs
-KLpcURDV68BcbAvlPFy
dept: "abc"
desc: "xyz"
name: "efg"
-asdasdasddsad
dept: "asda"
desc: "asd"
name: "adddd"
我试过了,但它返回了俱乐部"
I tried this but it returned "clubs"
mDatabase.child("clubs").orderByChild("name").equalTo("efg").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String clubkey =dataSnapshot.getKey();
推荐答案
那是因为您正在使用 ValueEventListener
.如果查询匹配多个子项,则返回所有这些子项的列表.即使只有一个匹配子项,它仍然是一个列表.由于您在该列表上调用 getKey()
,您将获得运行查询的位置的键.
That's because you're using a ValueEventListener
. If the query matches multiple children, it returns a list of all those children. Even if there's only a single matches child, it's still a list of one. And since you're calling getKey()
on that list, you get the key of the location where you ran the query.
要获取匹配子项的键,请遍历快照的子项:
To get the key of the matches children, loop over the children of the snapshot:
mDatabase.child("clubs")
.orderByChild("name")
.equalTo("efg")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String clubkey = childSnapshot.getKey();
但请注意,如果您假设俱乐部名称是唯一的,您不妨将俱乐部存储在他们的名称下,然后无需查询即可访问正确的俱乐部:
But note that if you assume that the club name is unique, you might as well store the clubs under their name and access the correct one without a query:
mDatabase.child("clubs")
.child("efg")
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String clubkey = dataSnapshot.getKey(); // will be efg
这篇关于如何从firebase中的值中获取密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!