简体   繁体   English

如何使用Java从Firebase检索新添加的子代的父键

[英]How to retrieve parent key of newly added child from Firebase using java

I want to retrieve "7753400075_Canada_twinpalms_||_twinpalms_20170824001545_F5BA7F33AD51CE283332001BEC409A46" key, How to do so? 我想检索“ 7753400075_Canada_twinpalms_ ||| _twinpalms_20170824001545_F5BA7F33AD51CE283332001BEC409A46”键,该怎么做? Here is my code... 这是我的代码...

ref.addValueEventListener(new ValueEventListener() { //addListenerForSingleValueEvent
                @Override
                public void onCancelled(DatabaseError arg0) {
                }
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Object response = dataSnapshot.getValue();
                    System.out.println("read data :"+response);
                }
            });
            ref.child("chatmessage").child("devicetoken").addChildEventListener(new ChildEventListener() {

                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
//                  Log.d(TAG, "onChildAdded:" + dataSnapshot.getKey());
//                  System.out.println("previousChildName :"+previousChildName);

                    }
                }
});

Here is the Firebase database example: 这是Firebase数据库示例:

这是Firebase数据库示例

I tried using child data snapshot method but did not worked. 我尝试使用子数据快照方法,但是没有用。 It returns all data. 它返回所有数据。 But i need to get only the new child added parent. 但是我只需要让新孩子添加父母。 Any help for this will be much appreciated. 任何帮助,将不胜感激。

To solve this, you need to filter your results. 为了解决这个问题,您需要过滤结果。 Assuming that chatmessage is a direct child of your Firebase database root, please use the following code: 假设chatmessage是Firebase数据库根目录的直接子级,请使用以下代码:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference deviceTokenRef = rootRef.child("chatmessage").child("devicetoken");
Query query = deviceTokenRef.orderByKey().limitToLast(1);
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String key = ds.getKey();
            Log.d("TAG", key);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(eventListener);

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

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