如何在Firebase Android中检索父键 [英] How to retrieve parent key in firebase android
问题描述
我要获取 houfxWvbwyVmbHX60IGjpNkZR9w2
密钥,怎么办?
I want to retrieve houfxWvbwyVmbHX60IGjpNkZR9w2
key , How to do?
这是相同的代码
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
第二张图片
我尝试使用子数据快照方法,但是没有用.任何帮助,将不胜感激.
I tried using child data snapshot method but did not worked. Any help for this will be much appreciated.
推荐答案
假设您有一个指向子代 rhZ4 ... wt2
的 DataSnapshot
,则可以调用 snapsthot.getRef().toString()
,它将返回类似 https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2
的内容.从那里可以提取父密钥.
Assuming you have a DataSnapshot
that points to the children rhZ4...wt2
, you can call snapsthot.getRef().toString()
which will return you something like https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2
. From there you can extract the parent key.
在您的示例中,使用 mQuery
查询数据库之后,在 onDataChange
内部,您具有 DataSnapshot
.
From your example, after you query the database using mQuery
, inside onDataChange
you have a DataSnapshot
.
因此,调用 dataSnapshot.getRef().toString()
将为您提供 https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2/以下
.
So calling dataSnapshot.getRef().toString()
will give you https://xxx.firebaseio.com/.../houfxWvbwyVmbHX60IGjpNkZR9w2/rhZ4...wt2/following
.
提取父键的代码(将其放入您的第一个 onDataChange
中):
Code to extract the parent key (put it inside your 1st onDataChange
):
String reference = dataSnapshot.getRef().toString();
String[] tokens = reference.split("/");
String parentKey = tokens[tokens.length - 3];
此 parentKey
应该是您的 houfxWvbwyVmbHX60IGjpNkZR9w2
.
这篇关于如何在Firebase Android中检索父键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!