如何在firebase android中检索父键

时间:2017-10-26 08:36:42

标签: android firebase firebase-realtime-database

我想检索houfxWvbwyVmbHX60IGjpNkZR9w2密钥,怎么办?

以下是相同

的代码
mQuery = mfollowing.orderByChild("following").equalTo(user_id);
mQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {


        final String key = dataSnapshot.getKey();

        mdatabaseUsers.child(user_id).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                DatabaseReference newfollscreen = mdatabaseFollwer.child(key).child(newPost.getKey());

                newfollscreen.child("screen").setValue(downloadUrl.toString());
                newfollscreen.child("engagement").setValue("NA");
                newfollscreen.child("url").setValue("NA");
                newfollscreen.child("uid").setValue(user_id);
                newfollscreen.child("name").setValue(dataSnapshot.child("name").getValue());
                newfollscreen.child("image").setValue(dataSnapshot.child("image").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {

                        if (task.isSuccessful()){

                            Toast.makeText(AddimageActivity.this, "Posted among your followers", Toast.LENGTH_SHORT).show();
                        }else {

                            Toast.makeText(AddimageActivity.this, "Error", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


    }

    @Override
    public void onCancelled (DatabaseError
       databaseError){

    }

});

以下是Firebase数据库

Here is the Firebase database

第二张图片

enter image description here

我尝试使用子数据快照方法,但没有奏效。任何帮助都将非常感激。

1 个答案:

答案 0 :(得分:0)

假设您有DataSnapshot指向孩子rhZ4...wt2,您可以致电snapsthot.getRef().toString(),这会返回https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2之类的内容。从那里你可以提取父键。

在您的示例中,使用mQuery查询数据库后,在onDataChange内您有一个DataSnapshot

所以致电dataSnapshot.getRef().toString()会给你https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2/following

提取父密钥的代码(将其放在第一个onDataChange内):

String reference = dataSnapshot.getRef().toString();
String[] tokens = reference.split("/");
String parentKey = tokens[tokens.length - 3];

parentKey应该是您的houfxWvbwyVmbHX60IGjpNkZR9w2