[英]How to get the key of a child node in Firebase Realtime Database after choosing a child randomly
I want to get the key of the child node in the Firebase Realtime Database, which is also the UID
.我想获取 Firebase Realtime Database 中子节点的key,也就是UID
。 I am randomly choosing a child node and now I want to get the key of that child so that I can do further operations on it.我随机选择一个子节点,现在我想获取该子节点的密钥,以便我可以对其进行进一步的操作。
databaseReferencePickers.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
int pickerCount = (int) dataSnapshot.getChildrenCount();
Random random = new Random();
int rand = random.nextInt(pickerCount);
Iterator itr = dataSnapshot.getChildren().iterator();
for(int i = 0; i <= rand; i++) {
itr.next();
}
pickerDetails = itr.next().toString();
ObjectMapper oMapper = new ObjectMapper();
map = oMapper.convertValue(itr.next(), Map.class);
//pickerUID = Objects.requireNonNull(map.get("key")).toString();
pickerUID = dataSnapshot.getKey();
Toast.makeText(OrderPickupActivity.this,pickerUID,Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(OrderPickupActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Can you please help me with it?你能帮我吗? Whenever I Toast the value of "PickerUID", I get the value as null .每当我吐司“PickerUID”的值时,我得到的值为null 。
I want to retrieve the key from the pickers section.我想从选择器部分检索密钥。
If you want to get a random uid
by attaching a listener on the Pickers
node, please use the following lines of code:如果您想通过在Pickers
节点上附加监听器来获取随机uid
,请使用以下代码行:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference pickersRef = rootRef.child("Pickers");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> uids = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
uids.add(uid);
}
String randomUid = new Random().nextInt(uids.size());
//Do what you need to do with this random uid
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "Error: ", task.getException()); //Don't ignore errors!
}
};
pickersRef.addListenerForSingleValueEvent(valueEventListener);
See, you have to iterate through the DataSnapshot
object using the getChildren()
method in order to obtain the results.看,您必须使用getChildren()
方法遍历DataSnapshot
object 才能获得结果。 However, this is not quite the best solution because you download the entire Pickers
node, in order to get a single random id.但是,这并不是最好的解决方案,因为您下载了整个Pickers
节点,以便获得单个随机 ID。 For a more appreciate solution, please also check my answer from the following post:如需更满意的解决方案,请同时查看我在以下帖子中的回答:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.