如何从firebase中获取关键值

如何从firebase中获取关键值

本文介绍了如何从firebase中获取关键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我知道Firebase中以下结构中的name字段包含efg时,如何获得密钥-KLpcURDV68BcbAvlPFy。

  clubs 
-KLpcURDV68BcbAvlPFy
dept:abc
desc:xyz
名称:efg
-asdasdasddsad
部门:asda
desc:asd
名称:adddd

我试过这个,但是它返回clubs。

$ $ $ $ $ $ $ mDatabase.child(clubs)。orderByChild(name) .equalTo(efg)。addListenerForSingleValueEvent(new ValueEventListener(){
@Override $ b $ public void onDataChange(DataSnapshot dataSnapshot){
String clubkey = dataSnapshot.getKey();


解决方案

这是因为您正在使用 ValueEventListener 。如果查询匹配多个孩子,它将返回所有这些孩子的列表。即使只有一个匹配孩子,还在一个列表。而且,由于您在该列表上调用了 getKey(),所以您可以获得运行查询的位置的关键字。


$ b $为了获得匹配儿童的关键字,循环快照的子节点:

  mDatabase.child( )
.orderByChild(name)
.equalTo(efg)
.addListenerForSingleValueEvent(new ValueEventListener(){
@Override $ b $ public void onDataChange (DataSnapshot dataSnapshot){
for(DataSnapshot childSnapshot:dataSnapshot.getChildren()){
String clubkey = childSnapshot.getKey();
b
$ b

  mDatabase.child(clubs)
.child(efg)
.addListenerForSingleValueEvent(new ValueEventListener(){
@Override
public void onDataChange(DataSnapshot dataSnapshot){
String clubkey = dataSnapshot.getKey(); //将会是


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();
解决方案

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中获取关键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:41