简体   繁体   中英

Exception when ordering query by nested data with Firebase Android API

According to the Firebase documentation, it should be possible to order a query by a deeply nested child by passing the full path to the orderByChild() method like this

Firebase ref = new Firebase("https://dinosaur-facts.firebaseio.com/dinosaurs");
Query queryRef = ref.orderByChild("dimensions/height");
queryRef.addChildEventListener(new ChildEventListener() {
    @Override
    public void onChildAdded(DataSnapshot snapshot, String previousChild) {
        DinosaurFacts facts = snapshot.getValue(DinosaurFacts.class);
        System.out.println(snapshot.getKey() + " was " + facts.getHeight() + " meters tall");
    }
});

But calling orderByChild("dinosaurs/height") throws a FirebaseException with the message Invalid key: dinosaurs/height. Keys must not contain '/', '.', '#', '$', '[', or ']' Invalid key: dinosaurs/height. Keys must not contain '/', '.', '#', '$', '[', or ']' .

Indeed, the key is rejected by the following firebase method

private static final Pattern INVALID_KEY_REGEX = Pattern.compile("[\\[\\]\\.#\\$\\/\\u0000-\\u001F\\u007F]");

private static boolean isValidKey(String key) {
    return key.equals(".info") || !INVALID_KEY_REGEX.matcher(key).find();
}

What is the correct way of querying using the full path of an object?

The ability to order by a nested child was added in version 2.4 of the Firebase SDK for Java .

I just tried using a / on an older version of the SDK, and get the same error as you have. So my best bet is that you forgot to update your project to use Firebase SDK version 2.4.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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