如何在 Firebase 实时数据库(Android 开发)中获取特定子项的键值?
Posted
技术标签:
【中文标题】如何在 Firebase 实时数据库(Android 开发)中获取特定子项的键值?【英文标题】:How to get the key value of a specific child in the Firebase Realtime database (Android Development)? 【发布时间】:2021-12-15 16:16:33 【问题描述】:如何获取 Firebase 实时数据库中特定子项的键值(android 开发)? 我想根据所选主题获取特定键的值。假设如果用户选择 java 那么我想获得 '-MnLZAaa1pmVpRusEG8s'(在蓝色框中)。我试图获取列表中的主题名称和主题唯一键,然后将其与用户选择的字符串进行比较,但不知道为什么我得到一个空值。我该怎么做?
public String getSubjectUuid()
List<String> subjectNamesList = new ArrayList<>();
List<String> subjectUuidList = new ArrayList<>();
DatabaseReference addedSubjectReference = FirebaseDatabase
.getInstance()
.getReference(classCreatorPhoneNo + "/" + "class_list" + "/" + classUuid + "/" + "added_subject");
addedSubjectReference
.addChildEventListener(new ChildEventListener()
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName)
if (snapshot.exists())
subjectNamesList.add(snapshot.child("subject_name").getValue(String.class));
subjectUuidList.add(snapshot.child("subject_uuid").getValue(String.class));
@Override
public void onChildChanged(@NonNull DataSnapshot snapshot, @Nullable String previousChildName)
@Override
public void onChildRemoved(@NonNull DataSnapshot snapshot)
@Override
public void onChildMoved(@NonNull DataSnapshot snapshot, @Nullable String previousChildName)
@Override
public void onCancelled(@NonNull DatabaseError error)
);
for (int i = 0; i < subjectNamesList.size(); i++)
if (selectedSubject.equals(subjectNamesList.get(i)))
classKey = subjectUuidList.get(i);
break;
return classKey;
【问题讨论】:
【参考方案1】:您正在寻找use a query 对您的subject_name
字段进行排序/过滤。像这样的东西应该可以解决问题:
addedSubjectReference
.orderByChild("subject_name") // ? First order on a property
.equalTo("java") // ? Then filter on a value
.addChildEventListener(new ChildEventListener()
@Override
public void onChildAdded(@NonNull DataSnapshot snapshot, @Nullable String previousChildName)
//if (snapshot.exists()) // ? This is not needed inside `onChildAdded`
subjectNamesList.add(snapshot.child("subject_name").getValue(String.class));
subjectUuidList.add(snapshot.child("subject_uuid").getValue(String.class));
//
【讨论】:
以上是关于如何在 Firebase 实时数据库(Android 开发)中获取特定子项的键值?的主要内容,如果未能解决你的问题,请参考以下文章
如何将我的 Firebase 实时数据库转移到 Firebase Cloud Firestore