LiveData<DataSnapshot> questBadgeData = questViewModel.getBadgeSnapshotLiveData(questViewModel.getQuestId());
Log.d("sad","score calc quest id "+questViewModel.getQuestId());
questBadgeData.observe(getViewLifecycleOwner(), new Observer<DataSnapshot>() {
@Override
public void onChanged(DataSnapshot dataSnapshot) {
String badgeID = dataSnapshot.getKey();
Log.d("sad","badge id "+badgeID);
//String icon = dataSnapshot.child("icon").getValue().toString();
//String name = dataSnapshot.child("name").getValue().toString();
//questViewModel.setBadgeData(badgeID,icon,name);
questViewModel.setBadgeData(badgeID,"dummy","dummy");
}
});
这是我的Firebase数据库的结构:
@NonNull
public LiveData<DataSnapshot> getBadgeSnapshotLiveData(String qid) {
Query query = dbBadge.orderByChild("questid").equalTo(qid);
return new FirebaseQueryLiveData(query);
}
这是我的FirebaseQueryLiveData类
public class FirebaseQueryLiveData extends LiveData<DataSnapshot> {
private static final String TAG = "FirebaseQueryLiveData";
private final Query query;
private final MyValueEventListener listener = new MyValueEventListener();
public FirebaseQueryLiveData(Query query) {
this.query = query;
}
public FirebaseQueryLiveData(DatabaseReference ref) {
this.query = ref;
}
@Override
protected void onActive() {
Log.d(TAG, "onActive");
query.addValueEventListener(listener);
}
private class MyValueEventListener implements ValueEventListener {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
setValue(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "Can't listen to query " + query, databaseError.toException());
}
}
}
据我所知,当我打印日志中的批次ID时,我应该得到'b1',而当questid ='q1'时,我应该得到'b1'。
2020-06-30 17:15:21.864 29487-29487/com.example.activedash D/sad: score calc quest id q1
2020-06-30 17:15:21.916 29487-29487/com.example.activedash D/sad: badge id badge
当我只是将密钥作为child(key)而不是orderByChild()时,这很好,但是我需要通过orderByChild()获取徽章的密钥
@NonNull
public LiveData<DataSnapshot> getBadgeSnapshotLiveData(String qid) {
Query query = dbBadge.child("b1");
return new FirebaseQueryLiveData(query);
}
答案 0 :(得分:0)
对Firebase数据库执行查询时,可能会有多个结果。因此,快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。
您的onDataChange
需要通过遍历dataSnapshot.getChildren()
来处理该列表。因此,如果您确实只期望得到一个结果,那就是:
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
setValue(snapshot);
}
}