【发布时间】:2016-09-18 23:19:24
【问题描述】:
所以我的后端使用了 firebase。我的目标是将用户匹配添加到用户 ID。但是,当用户最初注册时,他们没有匹配项。我要做的是检查用户子项中是否存在“匹配”子项,如果不创建列表子项并存储第一个匹配项。但是,如果它已经存在,则只需添加匹配项。这是我的代码:
public void setMatch(final String match){
final Firebase ref = new Firebase("FIREBASEURL");
final Firebase userRef = ref.child("Flights").child(userName);
userRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
System.out.println("does the child exist? " + dataSnapshot.child("matches").exists());
if(!dataSnapshot.child("matches").exists()){
ArrayList<String> matches = new ArrayList<String>();
matches.add(match);
Firebase matchesRef = userRef.child("matches");
matchesRef.setValue(matches);
userRef.removeEventListener(this);
}else if(dataSnapshot.child("matches").exists()){
Map<String, Object> matches = new HashMap<>();
matches.put("matches", match);
userRef.child("matches").push().setValue(matches);
userRef.removeEventListener(this);
}
}
@Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
当前,该值被添加两次(如果字段已经存在,则调用 else if 两次/如果不存在则调用它)。我不确定我做错了什么。
【问题讨论】:
标签: java android firebase firebase-realtime-database