Firebase returning keys of child node in different orders on different devices/Android versions

后端 未结 1 966
南旧
南旧 2020-12-11 09:23

I am getting a snapshot of the data from my Firebase database to retrieve a users list, but the order of the keys being returned is different depending on the Android versi

相关标签:
1条回答
  • 2020-12-11 10:05

    The documentation for Firebase's REST API contains this warning:

    When using the REST API, the filtered results are returned in an undefined order since JSON interpreters don't enforce any ordering. If the order of your data is important you should sort the results in your application after they are returned from Firebase.

    In other words: the properties in a JSON object can be in any order. A JSON parser is free to re-arrange them as it sees fit.

    You are not using the REST API, but the Firebase Android SDK. All the Firebase SDKs take care if hiding such re-ordering from you or (when hiding it is not possible) telling you explicitly what the order is (e.g. the previousChildName argument to the onChildAdded callback)

    But from the data you're showing it seems like you're parsing the output from dataSnapshot.toString(). While this is totally valid, it does mean that you're choosing to handle the ordering yourself. In general it's best to stick to using the methods of the Firebase Android SDK, since they handle things like ordering for you:

    public void onDataChange(DataSnapshot snapshot) {
      for (DataSnapshot friendSnapshot: snapshot.getChildren()) {
        System.out.println(friendSnapshot.child("NameOfFriend").getValue());
      }
    } 
    

    Update

    From your update it seems like you have a query on users and then want to also loop over their friends. With the Firebase Android API you'd do that with:

    Firebase ref = new Firebase("https://myFirebaseID.firebaseio.com");
    final Firebase userRef = ref.child("users");
    userRef.addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot userSnapshot) {
        DataSnapshot friendsSnapshot = userSnapshot.child("friends");
        for (DataSnapshot friendSnapshot : friendsSnapshot.getChildren()) {
          System.out.println(friendSnapshot.child("NameOfFriend").getValue());
        }
      }
    });
    
    0 讨论(0)
提交回复
热议问题