简体   繁体   English

Firebase Android中的orderByChild; 无法正常工作

[英]Firebase orderByChild in android; can't get it to work

I have data structure as: 我的数据结构为:

https://law-apps-44h221543638e.firebaseio.com/apps to promote/0/ >> name:"First App", package:"fra"
https://law-apps-44h221543638e.firebaseio.com/apps to promote/1/ >> name:"Second App", package:"sca"
https://law-apps-44h221543638e.firebaseio.com/apps to promote/2/ >> name:"Third App", package:"tha"

and I query it using 我用它查询

Firebase myFirebaseReference = new Firebase("https://law-apps-44h221543638e.firebaseio.com/apps to promote");
Query queryRef = myFirebaseReference.orderByChild("name");

queryRef.addListenerForSingleValueEvent(new ValueEventListener() { // override methods })

But it returns the data in the same order ie sorted by the first child (1,2,3, etc.) How should I query it so it sorts the data by the "name" tag of each child? 但是它以相同的顺序返回数据,即按第一个子项(1、2、3等)排序。如何查询它,以便按每个子项的“名称”标签对数据进行排序?

Ok so I found the answer to this question and I am writing it so others may benefit from it. 好的,所以我找到了这个问题的答案,并且正在编写,以便其他人可以从中受益。 I was using an older technique wherein I was finding from datasnapshot my apps using their parents' numbers and due to this, I was delibrately undoing the ordering. 我使用的是一种较旧的技术,在该技术中,我使用父母的编号从数据快照中找到了我的应用程序,因此,我故意取消了排序。

Now I have used dataSnapshot.getChildren().iterator() and it is now working correctly. 现在,我使用了dataSnapshot.getChildren()。iterator(),它现在可以正常工作。 Here's the code: 这是代码:

Query queryRef = myFirebaseReference.orderByChild("name");

    queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

    String name;
    String my_package;

    long lengthOfForLoop = dataSnapshot.getChildrenCount();
    Iterator<DataSnapshot> child = dataSnapshot.getChildren().iterator();
    for (int i = 0; i < lengthOfForLoop; i++) {
            DataSnapshot next = child.next();
            name = next.child("name").getValue(String.class);
            my_package = next.child("package").getValue(String.class);
              // do something with this data.
               }
        }
    });
}

thanks, Usman! 谢谢,乌斯曼!

I used the same code with the children iterable collection in a for loop. 我在for循环中对子级可迭代集合使用了相同的代码。 This code was worked for me (in Kotlin): 这段代码为我工作(在Kotlin中):

 accountsReference.child(accountId).child("actions").orderByChild("actionPosition").addListenerForSingleValueEvent( object : ValueEventListener {
            override fun onDataChange(var1: DataSnapshot) {
                if (var1.children != null) {
                    for (actionsEntries in var1.children) {
                       ...
                    }
                }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM